1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.cms.security;
35
36 import org.mindrot.jbcrypt.BCrypt;
37 import java.security.MessageDigest;
38 import java.security.NoSuchAlgorithmException;
39
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 public final class Digester {
63
64 public static final String SHA1 = "SHA-1";
65
66 public static final String MD5 = "MD5";
67
68
69
70
71
72 public static final String SHA256 = "SHA-256";
73
74 public static final String SHA384 = "SHA-384";
75
76 public static final String SHA512 = "SHA-512";
77
78 private static Logger log = LoggerFactory.getLogger(Digester.class);
79
80
81
82
83 private Digester() {
84
85 }
86
87 public static String getDigest(String data, String algorithm) throws NoSuchAlgorithmException {
88 MessageDigest md = MessageDigest.getInstance(algorithm);
89 md.reset();
90 return new String(md.digest(data.getBytes()));
91 }
92
93 public static byte[] getDigest(byte[] data, String algorithm) throws NoSuchAlgorithmException {
94 MessageDigest md = MessageDigest.getInstance(algorithm);
95 md.reset();
96 return md.digest(data);
97 }
98
99
100
101
102 public static String getSHA1Hex(String data) {
103 try {
104 String result = Digester.getDigest(data, Digester.SHA1);
105 return Digester.toHEX(result);
106 }
107 catch (NoSuchAlgorithmException e) {
108 log.error(e.getMessage(), e);
109 }
110 return data;
111 }
112
113
114
115
116 public static String getMD5Hex(String data) {
117 try {
118 String result = Digester.getDigest(data, Digester.MD5);
119 return Digester.toHEX(result);
120 }
121 catch (NoSuchAlgorithmException e) {
122 log.error(e.getMessage(), e);
123 }
124 return data;
125 }
126
127
128
129
130
131
132 public static String toHEX(String data) {
133 return Digester.toHEX(data.getBytes());
134 }
135
136
137
138
139
140
141 public static String toHEX(byte[] data) {
142 StringBuffer hexValue = new StringBuffer();
143 char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
144 for (int i = 0; i < data.length; i++) {
145 byte byteValue = data[i];
146 hexValue.append(digits[(byteValue & 0xf0) >> 4]);
147 hexValue.append(digits[byteValue & 0x0f]);
148 }
149 return hexValue.toString();
150 }
151
152 public static String getBCrypt(String text) {
153
154
155 String hashed = BCrypt.hashpw(text, BCrypt.gensalt(12));
156 return hashed;
157 }
158
159 public static boolean matchBCrypted(String candidate, String hash) {
160
161
162 return BCrypt.checkpw(candidate, hash);
163 }
164 }