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
14 changes: 13 additions & 1 deletion src/main/java/com/bitpay/sdk/util/KeyUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,12 @@ public static String sign(
return result;
}

private static boolean isHexDigit(char hex) {
return (hex >= '0' && hex <= '9')
|| (hex >= 'A' && hex <= 'F')
|| (hex >= 'a' && hex <= 'f');
}

private static int getHexVal(char hex) {
int val = hex;
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
Expand All @@ -321,7 +327,13 @@ public static byte[] hexToBytes(String hex) throws BitPayGenericException {
byte[] arr = new byte[hex.length() >> 1];

for (int i = 0; i < hex.length() >> 1; ++i) {
arr[i] = (byte) ((getHexVal(hexArray[i << 1]) << 4) + (getHexVal(hexArray[(i << 1) + 1])));
char high = hexArray[i << 1];
char low = hexArray[(i << 1) + 1];
if (!isHexDigit(high) || !isHexDigit(low)) {
BitPayExceptionProvider.throwGenericExceptionWithMessage(
"Error: The binary key contains a non-hex digit");
}
arr[i] = (byte) ((getHexVal(high) << 4) + (getHexVal(low)));
}

return arr;
Expand Down
6 changes: 6 additions & 0 deletions src/test/java/com/bitpay/sdk/util/KeyUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;


import com.bitpay.sdk.exceptions.BitPayGenericException;
Expand Down Expand Up @@ -46,6 +47,11 @@ public void it_should_convert_hex_to_bytes() throws BitPayGenericException {
assertArrayEquals(expectedBytes, actualBytes);
}

@Test
public void it_should_reject_a_non_hex_key_digit() {
assertThrows(BitPayGenericException.class, () -> KeyUtils.hexToBytes("0G"));
}

@Test
public void it_should_convert_bytes_to_hex() {
byte[] bytes = { 1, 35, 69, 103, -119, -85, -51, -17 };
Expand Down