1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.buildcache.hash;
20
21 import java.nio.charset.StandardCharsets;
22
23
24
25
26 @SuppressWarnings("checkstyle:MagicNumber")
27 public class HexUtils {
28
29 private static final byte[] ENC_ARRAY;
30 private static final byte[] DEC_ARRAY;
31
32 static {
33 ENC_ARRAY = new byte[16];
34 DEC_ARRAY = new byte[256];
35 for (byte i = 0; i < 10; i++) {
36 ENC_ARRAY[i] = (byte) ('0' + i);
37 DEC_ARRAY['0' + i] = i;
38 }
39 for (byte i = 10; i < 16; i++) {
40 ENC_ARRAY[i] = (byte) ('a' + i - 10);
41 DEC_ARRAY['a' + i - 10] = i;
42 DEC_ARRAY['A' + i - 10] = i;
43 }
44 }
45
46 public static String encode(byte[] hash) {
47 byte[] hexChars = new byte[hash.length * 2];
48 for (int j = 0; j < hash.length; j++) {
49 int v = hash[j] & 0xFF;
50 hexChars[j * 2] = ENC_ARRAY[v >>> 4];
51 hexChars[j * 2 + 1] = ENC_ARRAY[v & 0x0F];
52 }
53 return new String(hexChars, StandardCharsets.US_ASCII);
54 }
55
56 public static byte[] decode(String hex) {
57 int size = hex.length();
58 if (size % 2 != 0) {
59 throw new IllegalArgumentException("String length should be even");
60 }
61 byte[] bytes = new byte[size / 2];
62 int idx = 0;
63 for (int i = 0; i < size; i += 2) {
64 bytes[idx++] = (byte) (DEC_ARRAY[hex.charAt(i)] << 4 | DEC_ARRAY[hex.charAt(i + 1)]);
65 }
66 return bytes;
67 }
68
69 public static byte[] toByteArray(long value) {
70 byte[] result = new byte[8];
71 for (int i = 7; i >= 0; i--) {
72 result[i] = (byte) (value & 0xFF);
73 value >>= 8;
74 }
75 return result;
76 }
77 }