View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.buildcache.hash;
20  
21  import java.nio.charset.StandardCharsets;
22  
23  /**
24   * HexUtils
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  }