Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,17 @@ public static byte[] hexStringToByteArray(final String s) {
return null;
}
final int len = s.length();
if ((len & 1) != 0) {
throw new IllegalArgumentException("Hex string must contain an even number of characters");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the project convention for argument checks is Requires.requireTrue(cond, msg) from com.alipay.sofa.jraft.util.Requires (this class already uses Requires.requireNonNull in nextBytes). So this could be:

Requires.requireTrue((len & 1) == 0, "Hex string must contain an even number of characters");

}
final byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
final int high = Character.digit(s.charAt(i), 16);
final int low = Character.digit(s.charAt(i + 1), 16);
if (high < 0 || low < 0) {
throw new IllegalArgumentException("Hex string contains a non-hexadecimal character");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here — Requires.requireTrue(high >= 0 && low >= 0, ...). Also consider including the offending position in the message, e.g. "Hex string contains a non-hexadecimal character at index " + i. Index only, please — better not to echo the character or the input string itself, since this util may handle key material and the message could end up in logs.

}
bytes[i / 2] = (byte) ((high << 4) + low);
}
return bytes;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

public class BytesUtilTest {

Expand Down Expand Up @@ -97,7 +98,9 @@ public void testToHex() {
public void testHexStringToByteArray() {
Assert.assertNull(BytesUtil.hexStringToByteArray(null));

Assert.assertArrayEquals(new byte[] { -17, -5 }, BytesUtil.hexStringToByteArray("foob"));
Assert.assertArrayEquals(new byte[] { -17, -5 }, BytesUtil.hexStringToByteArray("effb"));
assertThrows(IllegalArgumentException.class, () -> BytesUtil.hexStringToByteArray("abc"));
assertThrows(IllegalArgumentException.class, () -> BytesUtil.hexStringToByteArray("foob"));
}

@Test
Expand Down
Loading