diff --git a/src/main/java/com/bitpay/sdk/util/KeyUtils.java b/src/main/java/com/bitpay/sdk/util/KeyUtils.java index c2f160a8..9b6d7c66 100644 --- a/src/main/java/com/bitpay/sdk/util/KeyUtils.java +++ b/src/main/java/com/bitpay/sdk/util/KeyUtils.java @@ -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)); @@ -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; diff --git a/src/test/java/com/bitpay/sdk/util/KeyUtilsTest.java b/src/test/java/com/bitpay/sdk/util/KeyUtilsTest.java index 563ff4d1..3a4592eb 100644 --- a/src/test/java/com/bitpay/sdk/util/KeyUtilsTest.java +++ b/src/test/java/com/bitpay/sdk/util/KeyUtilsTest.java @@ -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; @@ -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 };