forked from apache/activemq-artemis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultSensitiveStringCodec.java
273 lines (229 loc) · 9.24 KB
/
DefaultSensitiveStringCodec.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
/**
* A DefaultSensitiveDataCodec
*
* The default implementation of SensitiveDataCodec.
* This class is used when the user indicates in the config
* file to use a masked password but doesn't give a
* codec implementation.
*
* It supports one-way hash (digest) and two-way (encrypt-decrpt) algorithms
* The two-way uses "Blowfish" algorithm
* The one-way uses "PBKDF2" hash algorithm
*/
public class DefaultSensitiveStringCodec implements SensitiveDataCodec<String> {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static final String ALGORITHM = "algorithm";
public static final String BLOWFISH_KEY = "key";
public static final String ONE_WAY = "one-way";
public static final String TWO_WAY = "two-way";
public static final String KEY_SYSTEM_PROPERTY = "artemis.default.sensitive.string.codec.key";
private CodecAlgorithm algorithm = new BlowfishAlgorithm(Collections.EMPTY_MAP);
@Override
public String decode(Object secret) throws Exception {
return algorithm.decode((String) secret);
}
@Override
public String encode(Object secret) throws Exception {
return algorithm.encode((String) secret);
}
@Override
public void init(Map<String, String> params) throws Exception {
String algorithm = params.get(ALGORITHM);
if (algorithm == null || algorithm.equals(TWO_WAY)) {
//two way
this.algorithm = new BlowfishAlgorithm(params);
} else if (algorithm.equals(ONE_WAY)) {
this.algorithm = new PBKDF2Algorithm(params);
} else {
throw new IllegalArgumentException("Invalid algorithm: " + algorithm);
}
}
/**
* This main class is as documented on configuration-index.md, where the user can mask the password here. *
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Use: java -cp <classPath> org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec password-to-encode");
System.err.println("Error: no password on the args");
System.exit(-1);
}
DefaultSensitiveStringCodec codec = new DefaultSensitiveStringCodec();
Map<String, String> params = new HashMap<>();
Properties properties = System.getProperties();
synchronized (properties) {
for (final String name : properties.stringPropertyNames()) {
params.put(name, properties.getProperty(name));
}
}
codec.init(params);
Object encode = codec.encode(args[0]);
System.out.println("Encoded password (without quotes): \"" + encode + "\"");
}
@Override
public boolean verify(char[] inputValue, String storedValue) {
return algorithm.verify(inputValue, storedValue);
}
private abstract static class CodecAlgorithm {
protected Map<String, String> params;
CodecAlgorithm(Map<String, String> params) {
this.params = params;
}
public abstract String decode(String secret) throws Exception;
public abstract String encode(String secret) throws Exception;
public boolean verify(char[] inputValue, String storedValue) {
return false;
}
}
private class BlowfishAlgorithm extends CodecAlgorithm {
private byte[] internalKey = "clusterpassword".getBytes();
BlowfishAlgorithm(Map<String, String> params) {
super(params);
String key = params.get(BLOWFISH_KEY);
if (key != null) {
updateKey(key);
} else {
key = System.getProperty(KEY_SYSTEM_PROPERTY);
if (key != null && key.trim().length() > 0) {
logger.trace("Set key from system property {}", KEY_SYSTEM_PROPERTY);
updateKey(key);
}
}
}
private void updateKey(String key) {
this.internalKey = key.getBytes();
}
@Override
public String decode(String secret) throws Exception {
SecretKeySpec key = new SecretKeySpec(internalKey, "Blowfish");
byte[] encoding;
try {
encoding = new BigInteger(secret, 16).toByteArray();
} catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug(ex.getMessage(), ex);
}
throw new IllegalArgumentException("Password must be encrypted.");
}
if (encoding.length % 8 != 0) {
int length = encoding.length;
int newLength = ((length / 8) + 1) * 8;
int pad = newLength - length; // number of leading zeros
byte[] old = encoding;
encoding = new byte[newLength];
System.arraycopy(old, 0, encoding, pad, old.length);
}
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decode = cipher.doFinal(encoding);
return new String(decode);
}
@Override
public String encode(String secret) throws Exception {
SecretKeySpec key = new SecretKeySpec(internalKey, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encoding = cipher.doFinal(secret.getBytes());
BigInteger n = new BigInteger(encoding);
return n.toString(16);
}
@Override
public boolean verify(char[] inputValue, String storedValue) {
try {
return Objects.equals(storedValue, encode(String.valueOf(inputValue)));
} catch (Exception e) {
logger.debug("Exception on verifying:", e);
return false;
}
}
}
private static class PBKDF2Algorithm extends CodecAlgorithm {
private static final String SEPARATOR = ":";
private String sceretKeyAlgorithm = "PBKDF2WithHmacSHA1";
private String randomScheme = "SHA1PRNG";
private int keyLength = 64 * 8;
private int saltLength = 32;
private int iterations = 1024;
private SecretKeyFactory skf;
private static SecureRandom sr;
PBKDF2Algorithm(Map<String, String> params) throws NoSuchAlgorithmException {
super(params);
skf = SecretKeyFactory.getInstance(sceretKeyAlgorithm);
if (sr == null) {
sr = SecureRandom.getInstance(randomScheme);
}
}
@Override
public String decode(String secret) throws Exception {
throw new IllegalArgumentException("Algorithm doesn't support decoding");
}
public byte[] getSalt() {
byte[] salt = new byte[this.saltLength];
sr.nextBytes(salt);
return salt;
}
@Override
public String encode(String secret) throws Exception {
char[] chars = secret.toCharArray();
byte[] salt = getSalt();
StringBuilder builder = new StringBuilder();
builder.append(iterations).append(SEPARATOR).append(ByteUtil.bytesToHex(salt)).append(SEPARATOR);
PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, keyLength);
byte[] hash = skf.generateSecret(spec).getEncoded();
String hexValue = ByteUtil.bytesToHex(hash);
builder.append(hexValue);
return builder.toString();
}
@Override
public boolean verify(char[] plainChars, String storedValue) {
String[] parts = storedValue.split(SEPARATOR);
int originalIterations = Integer.parseInt(parts[0]);
byte[] salt = ByteUtil.hexToBytes(parts[1]);
byte[] originalHash = ByteUtil.hexToBytes(parts[2]);
PBEKeySpec spec = new PBEKeySpec(plainChars, salt, originalIterations, originalHash.length * 8);
byte[] newHash;
try {
newHash = skf.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException e) {
return false;
}
return Arrays.equals(newHash, originalHash);
}
}
}