1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.caches.memcached;
17
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20
21
22
23
24
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
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 }