|
6 | 6 | import java.security.MessageDigest; |
7 | 7 | import java.security.NoSuchAlgorithmException; |
8 | 8 | import java.util.Arrays; |
| 9 | +import org.apache.commons.codec.DecoderException; |
| 10 | +import org.apache.commons.codec.binary.Hex; |
9 | 11 | import org.stellar.sdk.exception.UnexpectedException; |
10 | 12 |
|
11 | 13 | /** |
|
14 | 16 | * <p>note: For some reason we need to make it public, but I don't recommend to use it directly. |
15 | 17 | */ |
16 | 18 | public class Util { |
17 | | - private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); |
18 | | - |
19 | 19 | /** |
20 | 20 | * Returns hex representation of <code>bytes</code> array. |
21 | 21 | * |
22 | 22 | * @param bytes byte array to convert to hex |
23 | | - * @return hex representation of the byte array |
| 23 | + * @return hex representation of the byte array (uppercase) |
24 | 24 | */ |
25 | 25 | public static String bytesToHex(byte[] bytes) { |
26 | | - char[] hexChars = new char[bytes.length * 2]; |
27 | | - for (int j = 0; j < bytes.length; j++) { |
28 | | - int v = bytes[j] & 0xFF; |
29 | | - hexChars[j * 2] = HEX_ARRAY[v >>> 4]; |
30 | | - hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; |
31 | | - } |
32 | | - return new String(hexChars); |
| 26 | + return Hex.encodeHexString(bytes, false); |
33 | 27 | } |
34 | 28 |
|
35 | 29 | /** |
36 | 30 | * Returns byte array representation of <code>hex</code> string. |
37 | 31 | * |
38 | 32 | * @param s hex string to convert to byte array |
39 | 33 | * @return byte array representation of the hex string |
| 34 | + * @throws IllegalArgumentException if the string contains non-hex characters or has odd length |
40 | 35 | */ |
41 | 36 | public static byte[] hexToBytes(String s) { |
42 | | - int len = s.length(); |
43 | | - byte[] data = new byte[len / 2]; |
44 | | - for (int i = 0; i < len; i += 2) { |
45 | | - data[i / 2] = |
46 | | - (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); |
| 37 | + try { |
| 38 | + return Hex.decodeHex(s); |
| 39 | + } catch (DecoderException e) { |
| 40 | + throw new IllegalArgumentException("Invalid hex string: " + s, e); |
47 | 41 | } |
48 | | - return data; |
49 | 42 | } |
50 | 43 |
|
51 | 44 | /** |
|
0 commit comments