37796
|
1 |
/*
|
|
2 |
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
|
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 |
*
|
|
5 |
* This code is free software; you can redistribute it and/or modify it
|
|
6 |
* under the terms of the GNU General Public License version 2 only, as
|
|
7 |
* published by the Free Software Foundation. Oracle designates this
|
|
8 |
* particular file as subject to the "Classpath" exception as provided
|
|
9 |
* by Oracle in the LICENSE file that accompanied this code.
|
|
10 |
*
|
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that
|
|
15 |
* accompanied this code).
|
|
16 |
*
|
|
17 |
* You should have received a copy of the GNU General Public License version
|
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
20 |
*
|
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
22 |
* or visit www.oracle.com if you need additional information or have any
|
|
23 |
* questions.
|
|
24 |
*/
|
|
25 |
|
|
26 |
package sun.security.provider;
|
|
27 |
|
|
28 |
import sun.security.util.Debug;
|
|
29 |
|
|
30 |
import java.security.*;
|
|
31 |
import java.util.Arrays;
|
|
32 |
import java.util.Objects;
|
|
33 |
import static java.security.DrbgParameters.Capability.*;
|
|
34 |
|
|
35 |
/**
|
|
36 |
* The abstract base class for all DRBGs.
|
|
37 |
* <p>
|
|
38 |
* This class creates 5 new abstract methods. 3 are defined by the SP800-90A:
|
|
39 |
* <ol>
|
|
40 |
* <li>{@link #generateAlgorithm(byte[], byte[])}
|
|
41 |
* <li>{@link #reseedAlgorithm(byte[], byte[])} (might not be supported)
|
|
42 |
* <li>{@link #instantiateAlgorithm(byte[])}
|
|
43 |
* </ol>
|
|
44 |
* and 2 for implementation purpose:
|
|
45 |
* <ol>
|
|
46 |
* <li>{@link #initEngine()}
|
|
47 |
* <li>{@link #chooseAlgorithmAndStrength}
|
|
48 |
* </ol>
|
|
49 |
* All existing {@link SecureRandomSpi} methods are implemented based on the
|
|
50 |
* methods above as final. The initialization process is divided into 2 phases:
|
|
51 |
* configuration is eagerly called to set up parameters, and instantiation
|
|
52 |
* is lazily called only when nextBytes or reseed is called.
|
|
53 |
* <p>
|
|
54 |
* Synchronized keyword should be added to all externally callable engine
|
|
55 |
* methods including {@link #engineReseed}, {@link #engineSetSeed}, and
|
|
56 |
* {@link #engineNextBytes} (but not {@link #engineGenerateSeed}).
|
|
57 |
* Internal methods like {@link #configure} and {@link #instantiateAlgorithm}
|
|
58 |
* are not synchronized. They will either be called in a constructor or
|
|
59 |
* in another synchronized method.
|
|
60 |
*/
|
|
61 |
public abstract class AbstractDrbg extends SecureRandomSpi {
|
|
62 |
|
|
63 |
private static final long serialVersionUID = 9L;
|
|
64 |
|
|
65 |
/**
|
|
66 |
* This field is not null if {@code -Djava.security.debug=securerandom} is
|
|
67 |
* specified on the command line. An implementation can print useful
|
|
68 |
* debug info.
|
|
69 |
*/
|
|
70 |
protected static final Debug debug = Debug.getInstance(
|
|
71 |
"securerandom", "drbg");
|
|
72 |
|
|
73 |
// Common working status
|
|
74 |
|
|
75 |
private transient boolean instantiated = false;
|
|
76 |
|
|
77 |
/**
|
|
78 |
* Reseed counter of a DRBG instance. A mechanism should increment it
|
|
79 |
* after each random bits generation and reset it in reseed. A mechanism
|
|
80 |
* does <em>not</em> need to compare it to {@link #reseedInterval}.
|
|
81 |
*/
|
|
82 |
protected transient int reseedCounter = 0;
|
|
83 |
|
|
84 |
// Mech features. If not same as below, must be redefined in constructor.
|
|
85 |
|
|
86 |
/**
|
|
87 |
* Default strength of a DRBG instance if it is not configured.
|
|
88 |
* 128 is considered secure enough now. A mechanism
|
|
89 |
* can change it in a constructor.
|
|
90 |
*
|
|
91 |
* Remember to sync with "securerandom.drbg.config" in java.security.
|
|
92 |
*/
|
|
93 |
protected static final int DEFAULT_STRENGTH = 128;
|
|
94 |
|
|
95 |
/**
|
|
96 |
* Mechanism name, say, {@code HashDRBG}. Must be set in constructor.
|
|
97 |
* This value will be used in {@code toString}.
|
|
98 |
*/
|
|
99 |
protected String mechName = "DRBG";
|
|
100 |
|
|
101 |
/**
|
|
102 |
* highest_supported_security_strength of this mechanism for all algorithms
|
|
103 |
* it supports. A mechanism should update the value in its constructor
|
|
104 |
* if the value is not 256.
|
|
105 |
*/
|
|
106 |
protected int highestSupportedSecurityStrength = 256;
|
|
107 |
|
|
108 |
/**
|
|
109 |
* Whether prediction resistance is supported. A mechanism should update
|
|
110 |
* the value in its constructor if it is <em>not</em> supported.
|
|
111 |
*/
|
|
112 |
protected boolean supportPredictionResistance = true;
|
|
113 |
|
|
114 |
/**
|
|
115 |
* Whether reseed is supported. A mechanism should update
|
|
116 |
* the value in its constructor if it is <em>not</em> supported.
|
|
117 |
*/
|
|
118 |
protected boolean supportReseeding = true;
|
|
119 |
|
|
120 |
// Strength features. If not same as below, must be redefined in
|
|
121 |
// chooseAlgorithmAndStrength. Among these, minLength and seedLen have no
|
|
122 |
// default value and must be redefined. If personalization string or
|
|
123 |
// additional input is not supported, set maxPersonalizationStringLength
|
|
124 |
// or maxAdditionalInputLength to -1.
|
|
125 |
|
|
126 |
/**
|
|
127 |
* Minimum entropy input length in bytes for this DRBG instance.
|
|
128 |
* Must be assigned in {@link #chooseAlgorithmAndStrength}.
|
|
129 |
*/
|
|
130 |
protected int minLength;
|
|
131 |
|
|
132 |
/**
|
|
133 |
* Maximum entropy input length in bytes for this DRBG instance.
|
|
134 |
* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not
|
|
135 |
* {@link Integer#MAX_VALUE}.
|
|
136 |
* <p>
|
|
137 |
* In theory this value (and the values below) can be bigger than
|
|
138 |
* {@code Integer.MAX_VALUE} but a Java array can only have an int32 index.
|
|
139 |
*/
|
|
140 |
protected int maxLength = Integer.MAX_VALUE;
|
|
141 |
|
|
142 |
/**
|
|
143 |
* Maximum personalization string length in bytes for this DRBG instance.
|
|
144 |
* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not
|
|
145 |
* {@link Integer#MAX_VALUE}.
|
|
146 |
*/
|
|
147 |
protected int maxPersonalizationStringLength = Integer.MAX_VALUE;
|
|
148 |
|
|
149 |
/**
|
|
150 |
* Maximum additional input length in bytes for this DRBG instance.
|
|
151 |
* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not
|
|
152 |
* {@link Integer#MAX_VALUE}.
|
|
153 |
*/
|
|
154 |
protected int maxAdditionalInputLength = Integer.MAX_VALUE;
|
|
155 |
|
|
156 |
/**
|
|
157 |
* max_number_of_bits_per_request in bytes for this DRBG instance.
|
|
158 |
* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not
|
|
159 |
* {@link Integer#MAX_VALUE}.
|
|
160 |
*/
|
|
161 |
protected int maxNumberOfBytesPerRequest = Integer.MAX_VALUE;
|
|
162 |
|
|
163 |
/**
|
|
164 |
* Maximum number of requests between reseeds for this DRBG instance.
|
|
165 |
* Should be assigned in {@link #chooseAlgorithmAndStrength} if it is not
|
|
166 |
* {@link Integer#MAX_VALUE}.
|
|
167 |
*/
|
|
168 |
protected int reseedInterval = Integer.MAX_VALUE;
|
|
169 |
|
|
170 |
|
|
171 |
/**
|
|
172 |
* Algorithm used by this instance (SHA-512 or AES-256). Must be assigned
|
|
173 |
* in {@link #chooseAlgorithmAndStrength}. This field is used in
|
|
174 |
* {@link #toString()} and {@link DRBG#algorithmName}.
|
|
175 |
*/
|
|
176 |
protected String algorithm;
|
|
177 |
|
|
178 |
// Configurable parameters
|
|
179 |
|
|
180 |
/**
|
|
181 |
* Security strength for this instance. Must be assigned in
|
|
182 |
* {@link #chooseAlgorithmAndStrength}. Should be at least the requested
|
|
183 |
* strength. Might be smaller than the highest strength
|
|
184 |
* {@link #algorithm} supports. Must not be -1.
|
|
185 |
*/
|
|
186 |
protected int securityStrength; // in bits
|
|
187 |
|
|
188 |
/**
|
|
189 |
* Strength requested in {@link DrbgParameters.Instantiation}.
|
|
190 |
* The real strength is based on it. Do not modify it in a mechanism.
|
|
191 |
*/
|
|
192 |
protected int requestedInstantiationSecurityStrength = -1;
|
|
193 |
|
|
194 |
/**
|
|
195 |
* The personalization string used by this instance. Set inside
|
|
196 |
* {@link #configure(SecureRandomParameters)} and
|
|
197 |
* can be used in a mechanism. Do not modify it in a mechanism.
|
|
198 |
*/
|
|
199 |
protected byte[] personalizationString;
|
|
200 |
|
|
201 |
/**
|
|
202 |
* The prediction resistance flag used by this instance. Set inside
|
|
203 |
* {@link #configure(SecureRandomParameters)}.
|
|
204 |
*/
|
|
205 |
private boolean predictionResistanceFlag;
|
|
206 |
|
|
207 |
// Non-standard configurable parameters
|
|
208 |
|
|
209 |
/**
|
|
210 |
* Whether a derivation function is used. Requested in
|
|
211 |
* {@link MoreDrbgParameters}. Only CtrDRBG uses it.
|
|
212 |
* Do not modify it in a mechanism.
|
|
213 |
*/
|
|
214 |
protected boolean usedf;
|
|
215 |
|
|
216 |
/**
|
|
217 |
* The nonce for this instance. Set in {@link #instantiateIfNecessary}.
|
|
218 |
* After instantiation, this field is not null. Do not modify it
|
|
219 |
* in a mechanism.
|
|
220 |
*/
|
|
221 |
protected transient byte[] nonce;
|
|
222 |
|
|
223 |
/**
|
|
224 |
* Requested nonce in {@link MoreDrbgParameters}. If set to null,
|
|
225 |
* nonce will be chosen by system, and a reinstantiated DRBG will get a
|
|
226 |
* new system-provided nonce.
|
|
227 |
*/
|
|
228 |
private byte[] requestedNonce;
|
|
229 |
|
|
230 |
/**
|
|
231 |
* Requested algorithm in {@link MoreDrbgParameters}.
|
|
232 |
* Do not modify it in a mechanism.
|
|
233 |
*/
|
|
234 |
protected String requestedAlgorithm;
|
|
235 |
|
|
236 |
/**
|
|
237 |
* The entropy source used by this instance. Set inside
|
|
238 |
* {@link #configure(SecureRandomParameters)}. This field
|
|
239 |
* can be null. {@link #getEntropyInput} will take care of null check.
|
|
240 |
*/
|
|
241 |
private transient EntropySource es;
|
|
242 |
|
|
243 |
// Five abstract methods for SP 800-90A DRBG
|
|
244 |
|
|
245 |
/**
|
|
246 |
* Decides what algorithm and strength to use (SHA-256 or AES-256,
|
|
247 |
* 128 or 256). Strength related fields must also be defined or redefined
|
|
248 |
* here. Called in {@link #configure}. A mechanism uses
|
|
249 |
* {@link #requestedAlgorithm},
|
|
250 |
* {@link #requestedInstantiationSecurityStrength}, and
|
|
251 |
* {@link #DEFAULT_STRENGTH} to decide which algorithm and strength to use.
|
|
252 |
* <p>
|
|
253 |
* If {@code requestedAlgorithm} is provided, it will always be used.
|
|
254 |
* If {@code requestedInstantiationSecurityStrength} is also provided,
|
|
255 |
* the algorithm will use the strength (an exception will be thrown if
|
|
256 |
* the strength is not supported), otherwise, the smaller one of
|
|
257 |
* the highest supported strength of the algorithm and the default strength
|
|
258 |
* will be used.
|
|
259 |
* <p>
|
|
260 |
* If {@code requestedAlgorithm} is not provided, an algorithm will be
|
|
261 |
* chosen that supports {@code requestedInstantiationSecurityStrength}
|
|
262 |
* (or {@code DEFAULT_STRENGTH} if there is no request).
|
|
263 |
* <p>
|
|
264 |
* Since every call to {@link #configure} will call this method,
|
|
265 |
* make sure to the calls do not contradict with each other.
|
|
266 |
* <p>
|
|
267 |
* Here are some examples of the algorithm and strength chosen (suppose
|
|
268 |
* {@code DEFAULT_STRENGTH} is 128) for HashDRBG:
|
|
269 |
* <pre>
|
|
270 |
* requested effective
|
|
271 |
* (SHA-1, -1) (SHA-1,128)
|
|
272 |
* (SHA-1, 112) (SHA-1,112)
|
|
273 |
* (SHA-1, 192) IAE
|
|
274 |
* (SHA-256, -1) (SHA-256,128)
|
|
275 |
* (SHA-256, 128) (SHA-256,128)
|
|
276 |
* (SHA-3, -1) IAE
|
|
277 |
* (null, -1) (SHA-256,128)
|
|
278 |
* (null, 112) (SHA-256,112)
|
|
279 |
* (null, 192) (SHA-256,192)
|
|
280 |
* (null, 256) (SHA-256,256)
|
|
281 |
* (null, 384) IAE
|
|
282 |
* </pre>
|
|
283 |
*
|
|
284 |
* @throws IllegalArgumentException if the requested parameters
|
|
285 |
* can not be supported or contradict with each other.
|
|
286 |
*/
|
|
287 |
protected abstract void chooseAlgorithmAndStrength();
|
|
288 |
|
|
289 |
/**
|
|
290 |
* Initiates security engines ({@code MessageDigest}, {@code Mac},
|
|
291 |
* or {@code Cipher}). Must be called in deserialization. Please note
|
|
292 |
* that before instantiation the algorithm might not be available yet.
|
|
293 |
* In this case, just return and this method will be called
|
|
294 |
* automatically at instantiation.
|
|
295 |
*/
|
|
296 |
protected abstract void initEngine();
|
|
297 |
|
|
298 |
/**
|
|
299 |
* Instantiates a DRBG. Called automatically before the first
|
|
300 |
* {@code nextBytes} call.
|
|
301 |
* <p>
|
|
302 |
* Note that the other parameters (nonce, strength, ps) are already
|
|
303 |
* stored inside at configuration.
|
|
304 |
*
|
|
305 |
* @param ei the entropy input, its length is already conditioned to be
|
|
306 |
* between {@link #minLength} and {@link #maxLength}.
|
|
307 |
*/
|
|
308 |
protected abstract void instantiateAlgorithm(byte[] ei);
|
|
309 |
|
|
310 |
/**
|
|
311 |
* The generate function.
|
|
312 |
*
|
|
313 |
* @param result fill result here, not null
|
|
314 |
* @param additionalInput additional input, can be null. If not null,
|
|
315 |
* its length is smaller than {@link #maxAdditionalInputLength}
|
|
316 |
*/
|
|
317 |
protected abstract void generateAlgorithm(
|
|
318 |
byte[] result, byte[] additionalInput);
|
|
319 |
|
|
320 |
/**
|
|
321 |
* The reseed function.
|
|
322 |
*
|
|
323 |
* @param ei the entropy input, its length is already conditioned to be
|
|
324 |
* between {@link #minLength} and {@link #maxLength}.
|
|
325 |
* @param additionalInput additional input, can be null. If not null,
|
|
326 |
* its length is smaller than {@link #maxAdditionalInputLength}
|
|
327 |
* @throws UnsupportedOperationException if reseed is not supported
|
|
328 |
*/
|
|
329 |
protected void reseedAlgorithm(
|
|
330 |
byte[] ei, byte[] additionalInput) {
|
|
331 |
throw new UnsupportedOperationException("No reseed function");
|
|
332 |
}
|
|
333 |
|
|
334 |
// SecureRandomSpi methods taken care of here. All final.
|
|
335 |
|
|
336 |
@Override
|
|
337 |
protected final void engineNextBytes(byte[] result) {
|
|
338 |
engineNextBytes(result, DrbgParameters.nextBytes(
|
|
339 |
-1, predictionResistanceFlag, null));
|
|
340 |
}
|
|
341 |
|
|
342 |
@Override
|
|
343 |
protected final void engineNextBytes(
|
|
344 |
byte[] result, SecureRandomParameters params) {
|
|
345 |
|
|
346 |
Objects.requireNonNull(result);
|
|
347 |
|
|
348 |
if (debug != null) {
|
|
349 |
debug.println(this, "nextBytes");
|
|
350 |
}
|
|
351 |
if (params instanceof DrbgParameters.NextBytes) {
|
|
352 |
|
|
353 |
// 800-90Ar1 9.3: Generate Process.
|
|
354 |
|
|
355 |
DrbgParameters.NextBytes dp = (DrbgParameters.NextBytes) params;
|
|
356 |
|
|
357 |
// Step 2: max_number_of_bits_per_request
|
|
358 |
if (result.length > maxNumberOfBytesPerRequest) {
|
|
359 |
// generateAlgorithm should be called multiple times to fill
|
|
360 |
// up result. Unimplemented since maxNumberOfBytesPerRequest
|
|
361 |
// is now Integer.MAX_VALUE.
|
|
362 |
}
|
|
363 |
|
|
364 |
// Step 3: check requested_security_strength
|
|
365 |
if (dp.getStrength() > securityStrength) {
|
|
366 |
throw new IllegalArgumentException("strength too high: "
|
|
367 |
+ dp.getStrength());
|
|
368 |
}
|
|
369 |
|
|
370 |
// Step 4: check max_additional_input_length
|
|
371 |
byte[] ai = dp.getAdditionalInput();
|
|
372 |
if (ai != null && ai.length > maxAdditionalInputLength) {
|
|
373 |
throw new IllegalArgumentException("ai too long: "
|
|
374 |
+ ai.length);
|
|
375 |
}
|
|
376 |
|
|
377 |
// Step 5: check prediction_resistance_flag
|
|
378 |
boolean pr = dp.getPredictionResistance();
|
|
379 |
if (!predictionResistanceFlag && pr) {
|
|
380 |
throw new IllegalArgumentException("pr not available");
|
|
381 |
}
|
|
382 |
|
|
383 |
instantiateIfNecessary(null);
|
|
384 |
|
|
385 |
// Step 7: Auto reseed
|
|
386 |
if (reseedCounter > reseedInterval || pr) {
|
|
387 |
reseedAlgorithm(getEntropyInput(pr), ai);
|
|
388 |
ai = null;
|
|
389 |
}
|
|
390 |
|
|
391 |
// Step 8, 10: Generate_algorithm
|
|
392 |
// Step 9: Unnecessary. reseedCounter only updated after generation
|
|
393 |
generateAlgorithm(result, ai);
|
|
394 |
|
|
395 |
// Step 11: Return
|
|
396 |
} else {
|
|
397 |
throw new IllegalArgumentException("unknown params type:"
|
|
398 |
+ params.getClass());
|
|
399 |
}
|
|
400 |
}
|
|
401 |
|
|
402 |
@Override
|
|
403 |
public final void engineReseed(SecureRandomParameters params) {
|
|
404 |
if (debug != null) {
|
|
405 |
debug.println(this, "reseed with params");
|
|
406 |
}
|
|
407 |
if (!supportReseeding) {
|
|
408 |
throw new UnsupportedOperationException("Reseed not supported");
|
|
409 |
}
|
|
410 |
if (params == null) {
|
|
411 |
params = DrbgParameters.reseed(predictionResistanceFlag, null);
|
|
412 |
}
|
|
413 |
if (params instanceof DrbgParameters.Reseed) {
|
|
414 |
DrbgParameters.Reseed dp = (DrbgParameters.Reseed) params;
|
|
415 |
|
|
416 |
// 800-90Ar1 9.2: Reseed Process.
|
|
417 |
|
|
418 |
// Step 2: Check prediction_resistance_request
|
|
419 |
boolean pr = dp.getPredictionResistance();
|
|
420 |
if (!predictionResistanceFlag && pr) {
|
|
421 |
throw new IllegalArgumentException("pr not available");
|
|
422 |
}
|
|
423 |
|
|
424 |
// Step 3: Check additional_input length
|
|
425 |
byte[] ai = dp.getAdditionalInput();
|
|
426 |
if (ai != null && ai.length > maxAdditionalInputLength) {
|
|
427 |
throw new IllegalArgumentException("ai too long: "
|
|
428 |
+ ai.length);
|
|
429 |
}
|
|
430 |
instantiateIfNecessary(null);
|
|
431 |
|
|
432 |
// Step 4: Get_entropy_input
|
|
433 |
// Step 5: Check step 4
|
|
434 |
// Step 6-7: Reseed_algorithm
|
|
435 |
reseedAlgorithm(getEntropyInput(pr), ai);
|
|
436 |
|
|
437 |
// Step 8: Return
|
|
438 |
} else {
|
|
439 |
throw new IllegalArgumentException("unknown params type: "
|
|
440 |
+ params.getClass());
|
|
441 |
}
|
|
442 |
}
|
|
443 |
|
|
444 |
/**
|
|
445 |
* Returns the given number of seed bytes. A DRBG always uses
|
|
446 |
* {@link SeedGenerator} to get an array with full-entropy.
|
|
447 |
* <p>
|
|
448 |
* The implementation is identical to SHA1PRNG's
|
|
449 |
* {@link SecureRandom#engineGenerateSeed}.
|
|
450 |
*
|
|
451 |
* @param numBytes the number of seed bytes to generate.
|
|
452 |
* @return the seed bytes.
|
|
453 |
*/
|
|
454 |
@Override
|
|
455 |
public final byte[] engineGenerateSeed(int numBytes) {
|
|
456 |
byte[] b = new byte[numBytes];
|
|
457 |
SeedGenerator.generateSeed(b);
|
|
458 |
return b;
|
|
459 |
}
|
|
460 |
|
|
461 |
/**
|
|
462 |
* Reseeds this random object with the given seed. A DRBG always expands
|
|
463 |
* or truncates the input to be between {@link #minLength} and
|
|
464 |
* {@link #maxLength} and uses it to instantiate or reseed itself
|
|
465 |
* (depending on whether the DRBG is instantiated).
|
|
466 |
*
|
|
467 |
* @param input the seed
|
|
468 |
*/
|
|
469 |
@Override
|
|
470 |
public final synchronized void engineSetSeed(byte[] input) {
|
|
471 |
if (debug != null) {
|
|
472 |
debug.println(this, "setSeed");
|
|
473 |
}
|
|
474 |
if (input.length < minLength) {
|
|
475 |
input = Arrays.copyOf(input, minLength);
|
|
476 |
} else if (input.length > maxLength) {
|
|
477 |
input = Arrays.copyOf(input, maxLength);
|
|
478 |
}
|
|
479 |
if (!instantiated) {
|
|
480 |
instantiateIfNecessary(input);
|
|
481 |
} else {
|
|
482 |
reseedAlgorithm(input, null);
|
|
483 |
}
|
|
484 |
}
|
|
485 |
|
|
486 |
// get_entropy_input
|
|
487 |
|
|
488 |
private byte[] getEntropyInput(boolean isPr) {
|
|
489 |
// Should the 1st arg be minEntropy or minLength?
|
|
490 |
//
|
|
491 |
// Technically it should be minEntropy, but CtrDRBG
|
|
492 |
// (not using derivation function) is so confusing
|
|
493 |
// (does it need only strength or seedlen of entropy?)
|
|
494 |
// that it's safer to assume minLength. In all other
|
|
495 |
// cases minLength equals to minEntropy.
|
|
496 |
return getEntropyInput(minLength, minLength, maxLength, isPr);
|
|
497 |
}
|
|
498 |
|
|
499 |
private byte[] getEntropyInput(int minEntropy, int minLength,
|
|
500 |
int maxLength, boolean pr) {
|
|
501 |
if (debug != null) {
|
|
502 |
debug.println(this, "getEntropy(" + minEntropy + "," + minLength +
|
|
503 |
"," + maxLength + "," + pr + ")");
|
|
504 |
}
|
|
505 |
EntropySource esNow = es;
|
|
506 |
if (esNow == null) {
|
|
507 |
esNow = pr ? SeederHolder.prseeder : SeederHolder.seeder;
|
|
508 |
}
|
|
509 |
return esNow.getEntropy(minEntropy, minLength, maxLength, pr);
|
|
510 |
}
|
|
511 |
|
|
512 |
// Defaults
|
|
513 |
|
|
514 |
/**
|
|
515 |
* The default {@code EntropySource} determined by system property
|
|
516 |
* "java.security.egd" or security property "securerandom.source".
|
|
517 |
* <p>
|
|
518 |
* This object uses {@link SeedGenerator#generateSeed(byte[])} to
|
|
519 |
* return a byte array containing {@code minLength} bytes. It is
|
|
520 |
* assumed to support prediction resistance and always contains
|
|
521 |
* full-entropy. A trusted application can update this field.
|
|
522 |
*/
|
|
523 |
private final static EntropySource defaultES =
|
|
524 |
(minE, minLen, maxLen, pr) -> {
|
|
525 |
byte[] result = new byte[minLen];
|
|
526 |
SeedGenerator.generateSeed(result);
|
|
527 |
return result;
|
|
528 |
};
|
|
529 |
|
|
530 |
private static class SeederHolder {
|
|
531 |
|
|
532 |
/**
|
|
533 |
* Default EntropySource for SecureRandom with prediction resistance,
|
|
534 |
*/
|
|
535 |
static final EntropySource prseeder;
|
|
536 |
|
|
537 |
/**
|
|
538 |
* Default EntropySource for SecureRandom without prediction resistance,
|
|
539 |
* which is backed by a DRBG whose EntropySource is {@link #prseeder}.
|
|
540 |
*/
|
|
541 |
static final EntropySource seeder;
|
|
542 |
|
|
543 |
static {
|
|
544 |
prseeder = defaultES;
|
|
545 |
// According to SP800-90C section 7, a DRBG without live
|
|
546 |
// entropy (drbg here, with pr being false) can instantiate
|
|
547 |
// another DRBG with weaker strength. So we choose highest
|
|
548 |
// strength we support.
|
|
549 |
HashDrbg first = new HashDrbg(new MoreDrbgParameters(
|
|
550 |
prseeder, null, "SHA-256", null, false,
|
|
551 |
DrbgParameters.instantiation(
|
|
552 |
256, NONE,
|
|
553 |
SeedGenerator.getSystemEntropy())));
|
|
554 |
seeder = (entropy, minLen, maxLen, pr) -> {
|
|
555 |
if (pr) {
|
|
556 |
// This SEI does not support pr
|
|
557 |
throw new IllegalArgumentException("pr not supported");
|
|
558 |
}
|
|
559 |
byte[] result = new byte[minLen];
|
|
560 |
first.engineNextBytes(result);
|
|
561 |
return result;
|
|
562 |
};
|
|
563 |
}
|
|
564 |
}
|
|
565 |
|
|
566 |
// Constructor called by overridden methods, initializer...
|
|
567 |
|
|
568 |
/**
|
|
569 |
* A constructor without argument so that an implementation does not
|
|
570 |
* need to always write {@code super(params)}.
|
|
571 |
*/
|
|
572 |
protected AbstractDrbg() {
|
|
573 |
// Nothing
|
|
574 |
}
|
|
575 |
|
|
576 |
/**
|
|
577 |
* A mechanism shall override this constructor to setup {@link #mechName},
|
|
578 |
* {@link #highestSupportedSecurityStrength},
|
|
579 |
* {@link #supportPredictionResistance}, {@link #supportReseeding}
|
|
580 |
* or other features like {@link #DEFAULT_STRENGTH}. Finally it shall
|
|
581 |
* call {@link #configure} on {@code params}.
|
|
582 |
*
|
|
583 |
* @param params the {@link SecureRandomParameters} object.
|
|
584 |
* This argument can be {@code null}.
|
|
585 |
* @throws IllegalArgumentException if {@code params} is
|
|
586 |
* inappropriate for this SecureRandom.
|
|
587 |
*/
|
|
588 |
protected AbstractDrbg(SecureRandomParameters params) {
|
|
589 |
// Nothing
|
|
590 |
}
|
|
591 |
|
|
592 |
/**
|
|
593 |
* Returns the current configuration as a {@link DrbgParameters.Instantiation}
|
|
594 |
* object.
|
|
595 |
*
|
|
596 |
* @return the curent configuration
|
|
597 |
*/
|
|
598 |
@Override
|
|
599 |
protected SecureRandomParameters engineGetParameters() {
|
|
600 |
// Or read from variable.
|
|
601 |
return DrbgParameters.instantiation(
|
|
602 |
securityStrength,
|
|
603 |
predictionResistanceFlag ? PR_AND_RESEED :
|
|
604 |
(supportReseeding ? RESEED_ONLY : NONE),
|
|
605 |
personalizationString);
|
|
606 |
}
|
|
607 |
|
|
608 |
/**
|
|
609 |
* Configure this DRBG. This method calls
|
|
610 |
* {@link #chooseAlgorithmAndStrength()} and {@link #initEngine()}
|
|
611 |
* but does not do the actual instantiation.
|
|
612 |
*
|
|
613 |
* @param params configuration, if null, default configuration (default
|
|
614 |
* strength, pr_false, no personalization string) is used.
|
|
615 |
* @throws IllegalArgumentException if {@code params} is
|
|
616 |
* inappropriate for this SecureRandom.
|
|
617 |
*/
|
|
618 |
protected final synchronized void configure(
|
|
619 |
SecureRandomParameters params) {
|
|
620 |
if (debug != null) {
|
|
621 |
debug.println(this, "configure " + this + " with " + params);
|
|
622 |
}
|
|
623 |
if (params == null) {
|
|
624 |
params = DrbgParameters.instantiation(-1, RESEED_ONLY, null);
|
|
625 |
}
|
|
626 |
if (params instanceof MoreDrbgParameters) {
|
|
627 |
MoreDrbgParameters m = (MoreDrbgParameters)params;
|
|
628 |
this.requestedNonce = m.nonce;
|
|
629 |
this.es = m.es;
|
|
630 |
this.requestedAlgorithm = m.algorithm;
|
|
631 |
this.usedf = m.usedf;
|
|
632 |
params = m.config;
|
|
633 |
}
|
|
634 |
if (params != null) {
|
|
635 |
if (params instanceof DrbgParameters.Instantiation) {
|
|
636 |
DrbgParameters.Instantiation inst =
|
|
637 |
(DrbgParameters.Instantiation) params;
|
|
638 |
|
|
639 |
// 800-90Ar1 9.1: Instantiate Process. Steps 1-5.
|
|
640 |
|
|
641 |
// Step 1: Check requested_instantiation_security_strength
|
|
642 |
if (inst.getStrength() > highestSupportedSecurityStrength) {
|
|
643 |
throw new IllegalArgumentException("strength too big: "
|
|
644 |
+ inst.getStrength());
|
|
645 |
}
|
|
646 |
|
|
647 |
// Step 2: Check prediction_resistance_flag
|
|
648 |
if (inst.getCapability().supportsPredictionResistance()
|
|
649 |
&& !supportPredictionResistance) {
|
|
650 |
throw new IllegalArgumentException("pr not supported");
|
|
651 |
}
|
|
652 |
|
|
653 |
// Step 3: Check personalization_string
|
|
654 |
byte[] ps = inst.getPersonalizationString();
|
|
655 |
if (ps != null && ps.length > maxPersonalizationStringLength) {
|
|
656 |
throw new IllegalArgumentException("ps too long: "
|
|
657 |
+ ps.length);
|
|
658 |
}
|
|
659 |
|
|
660 |
if (inst.getCapability().supportsReseeding()
|
|
661 |
&& !supportReseeding) {
|
|
662 |
throw new IllegalArgumentException("reseed not supported");
|
|
663 |
}
|
|
664 |
this.personalizationString = ps;
|
|
665 |
this.predictionResistanceFlag =
|
|
666 |
inst.getCapability().supportsPredictionResistance();
|
|
667 |
this.requestedInstantiationSecurityStrength = inst.getStrength();
|
|
668 |
} else {
|
|
669 |
throw new IllegalArgumentException("unknown params: "
|
|
670 |
+ params.getClass());
|
|
671 |
}
|
|
672 |
}
|
|
673 |
|
|
674 |
// Step 4: Set security_strength
|
|
675 |
chooseAlgorithmAndStrength();
|
|
676 |
instantiated = false;
|
|
677 |
|
|
678 |
// Step 5: no-op.
|
|
679 |
|
|
680 |
if (debug != null) {
|
|
681 |
debug.println(this, "configured " + this);
|
|
682 |
}
|
|
683 |
}
|
|
684 |
|
|
685 |
/**
|
|
686 |
* Instantiate if necessary,
|
|
687 |
*
|
|
688 |
* @param entropy a user-provided entropy, the length is already good.
|
|
689 |
* If null, will fetch entropy input automatically.
|
|
690 |
*/
|
|
691 |
private synchronized void instantiateIfNecessary(byte[] entropy) {
|
|
692 |
if (!instantiated) {
|
|
693 |
|
|
694 |
// 800-90Ar1 9.1: Instantiate Process. Steps 6-12.
|
|
695 |
|
|
696 |
// Step 6: Get_entropy_input
|
|
697 |
// Step 7: check error (getEntropyInput throw no exception now)
|
|
698 |
if (entropy == null) {
|
|
699 |
entropy = getEntropyInput(predictionResistanceFlag);
|
|
700 |
}
|
|
701 |
|
|
702 |
// Step 8. nonce
|
|
703 |
if (requestedNonce != null) {
|
|
704 |
nonce = requestedNonce;
|
|
705 |
} else {
|
|
706 |
nonce = NonceProvider.next();
|
|
707 |
}
|
|
708 |
initEngine();
|
|
709 |
|
|
710 |
// Step 9-11: Instantiate_algorithm
|
|
711 |
instantiateAlgorithm(entropy);
|
|
712 |
instantiated = true;
|
|
713 |
|
|
714 |
// Step 12: Return
|
|
715 |
}
|
|
716 |
}
|
|
717 |
|
|
718 |
// Nonce provider
|
|
719 |
|
|
720 |
private static class NonceProvider {
|
|
721 |
|
|
722 |
// 128 bits of nonce can be used by 256-bit strength DRBG
|
|
723 |
private static final byte[] block = new byte[16];
|
|
724 |
|
|
725 |
private static synchronized byte[] next() {
|
|
726 |
int k = 15;
|
|
727 |
while ((k >= 0) && (++block[k] == 0)) {
|
|
728 |
k--;
|
|
729 |
}
|
|
730 |
return block.clone();
|
|
731 |
}
|
|
732 |
}
|
|
733 |
|
|
734 |
// Misc
|
|
735 |
|
|
736 |
/** A handy method returning hexdump string with no colon or new line.
|
|
737 |
*
|
|
738 |
* @param in input byte array
|
|
739 |
* @return the hexdump string
|
|
740 |
*/
|
|
741 |
protected static String hex(byte[] in) {
|
|
742 |
StringBuilder sb = new StringBuilder();
|
|
743 |
for (byte b : in) {
|
|
744 |
sb.append(String.format("%02x", b&0xff));
|
|
745 |
}
|
|
746 |
return sb.toString();
|
|
747 |
}
|
|
748 |
|
|
749 |
/**
|
|
750 |
* Returns the smallest standard strength (112, 128, 192, 256) that is
|
|
751 |
* greater or equal to the input.
|
|
752 |
*
|
|
753 |
* @param input the input strength
|
|
754 |
* @return the standard strength
|
|
755 |
*/
|
|
756 |
protected static int getStandardStrength(int input) {
|
|
757 |
if (input <= 112) return 112;
|
|
758 |
if (input <= 128) return 128;
|
|
759 |
if (input <= 192) return 192;
|
|
760 |
if (input <= 256) return 256;
|
|
761 |
throw new IllegalArgumentException("input too big: " + input);
|
|
762 |
}
|
|
763 |
|
|
764 |
@Override
|
|
765 |
public String toString() {
|
|
766 |
return mechName + "," + algorithm
|
|
767 |
+ "," + securityStrength + ","
|
|
768 |
+ (predictionResistanceFlag ? "pr_and_reseed"
|
|
769 |
: (supportReseeding ? "reseed_only" : "none"));
|
|
770 |
}
|
|
771 |
}
|