View Javadoc
1   /*
2    *    Copyright 2012-2022 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.caches.memcached;
17  
18  import java.security.MessageDigest;
19  import java.security.NoSuchAlgorithmException;
20  
21  /**
22   * Got from https://github.com/raykrueger/hibernate-memcached
23   *
24   * @author Ray Krueger
25   */
26  public final class StringUtils {
27  
28    private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
29        'f' };
30  
31    private StringUtils() {
32      // Prevent Instantiation
33    }
34  
35    public static String sha1Hex(String data) {
36      if (data == null) {
37        throw new IllegalArgumentException("data must not be null");
38      }
39  
40      byte[] bytes = digest("SHA1", data);
41  
42      return toHexString(bytes);
43    }
44  
45    private static String toHexString(byte[] bytes) {
46      int l = bytes.length;
47  
48      char[] out = new char[l << 1];
49  
50      for (int i = 0, j = 0; i < l; i++) {
51        out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
52        out[j++] = DIGITS[0x0F & bytes[i]];
53      }
54  
55      return new String(out);
56    }
57  
58    private static byte[] digest(String algorithm, String data) {
59      MessageDigest digest;
60      try {
61        digest = MessageDigest.getInstance(algorithm);
62      } catch (NoSuchAlgorithmException e) {
63        throw new RuntimeException(e);
64      }
65  
66      return digest.digest(data.getBytes());
67    }
68  
69  }