/* 2 * @(#)SecureRandom.java 1.47 03/12/19 3 * 4 * Copyright 2004 Sun Microsystems, Inc. All rights reserved. 5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 6 */ package java.security; import java.util.*; import java.security.Provider.Service; import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; /** 18 *
This class provides a cryptographically strong random number 19 * generator (RNG). Many implementations are in the form of a pseudo-random 20 * number generator (PRNG), which means they use a deterministic algorithm 21 * to produce a pseudo-random sequence from a true random seed. 22 * Other implementations may produce true random numbers 23 * and yet others may use a combination of both techniques. 24 * 25 *
A cryptographically strong random number 26 * minimally complies with the statistical random number generator tests 27 * specified in 28 * FIPS 140-2, Security Requirements for Cryptographic Modules, 29 * section 4.9.1. 30 * Additionally, SecureRandom must produce non-deterministic 31 * output and therefore it is required that the seed material be unpredictable 32 * and that output of SecureRandom be cryptographically strong sequences as 33 * described in 34 * RFC 1750: Randomness Recommendations for Security. 35 * 36 *
Like other algorithm-based classes in Java Security, SecureRandom
37 * provides implementation-independent algorithms, whereby a caller
38 * (application code) requests a particular RNG algorithm
39 * and is handed back a SecureRandom object for that algorithm. It is
40 * also possible, if desired, to request a particular algorithm from a
41 * particular provider. See the getInstance methods.
42 *
43 *
Thus, there are two ways to request a SecureRandom object: by 44 * specifying either just an algorithm name, or both an algorithm name 45 * and a package provider. 46 * 47 *
51 * SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
52 *
53 * the system will determine if there is an implementation of the algorithm
54 * requested available in the environment, and if there is more than one, if
55 * there is a preferred one.56 * 57 *
59 * SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
60 *
61 * the system will determine if there is an implementation of the
62 * algorithm in the package requested, and throw an exception if there
63 * is not.
64 *
65 * The SecureRandom implementation attempts to completely
68 * randomize the internal state of the generator itself unless
69 * the caller follows the call to a getInstance method
70 * with a call to the setSeed method:
71 *
72 * SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
73 * random.setSeed(seed);
74 *
75 *
76 * After the caller obtains the SecureRandom object from the
77 * getInstance call, it can call nextBytes
78 * to generate random bytes:
79 *
80 * byte bytes[] = new byte[20]; 81 * random.nextBytes(bytes); 82 *83 * 84 *
The caller may also invoke the generateSeed method
85 * to generate a given number of seed bytes (to seed other random number
86 * generators, for example):
87 *
88 * byte seed[] = random.generateSeed(20); 89 *90 * 91 * @see java.security.SecureRandomSpi 92 * @see java.util.Random 93 * 94 * @version 1.47, 12/19/03 95 * @author Benjamin Renaud 96 * @author Josh Bloch 97 */ public final class SecureRandom extends java.util.Random { /** 102 * The provider. 103 * 104 * @serial 105 * @since 1.2 106 */ private Provider provider = null; /** 110 * The provider implementation. 111 * 112 * @serial 113 * @since 1.2 14 */ private SecureRandomSpi secureRandomSpi = null; /* 118 * The algorithm name of null if unknown. 119 * 120 * @serial 121 * @since 1.5 122 */ private String algorithm; // Seed Generator private static SecureRandom seedGenerator = null; /** 129 *
By using this constructor, the caller obtains a SecureRandom object 130 * containing the implementation from the highest-priority installed 131 * provider that has a SecureRandom implementation. 132 * 133 *
Note that this instance of SecureRandom has not been seeded.
134 * A call to the setSeed method will seed the SecureRandom
135 * object. If a call is not made to setSeed, the first call
136 * to the nextBytes method will force the SecureRandom object
137 * to seed itself.
138 *
139 *
This constructor is provided for backwards compatibility.
140 * The caller is encouraged to use one of the alternative
141 * getInstance methods to obtain a SecureRandom object.
142 */
public SecureRandom() {
/*
145 * This call to our superclass constructor will result in a call
146 * to our own setSeed method, which will return
147 * immediately when it is passed zero.
148 */
super(0);
getDefaultPRNG(false, null);
}
/**
54 *
By using this constructor, the caller obtains a SecureRandom object 155 * containing the implementation from the highest-priority installed 156 * provider that has a SecureRandom implementation. This constructor 157 * uses a user-provided seed in 158 * preference to the self-seeding algorithm referred to in the empty 159 * constructor description. It may be preferable to the empty constructor 160 * if the caller has access to high-quality random bytes from some physical 161 * device (for example, a radiation detector or a noisy diode). 162 * 163 *
This constructor is provided for backwards compatibility.
164 * The caller is encouraged to use one of the alternative
165 * getInstance methods to obtain a SecureRandom object, and
166 * then to call the setSeed method to seed it.
167 *
168 * @param seed the seed.
169 */
public SecureRandom(byte seed[]) {
super(0);
getDefaultPRNG(true, seed);
}
private void getDefaultPRNG(boolean setSeed, byte[] seed) {
String prng = getPrngAlgorithm();
if (prng == null) {
// bummer, get the SUN implementation
prng = "SHA1PRNG";
this.secureRandomSpi = new sun.security.provider.SecureRandom();
this.provider = new sun.security.provider.Sun();
if (setSeed) {
this.secureRandomSpi.engineSetSeed(seed);
}
} else {
try {
SecureRandom random = SecureRandom.getInstance(prng);
this.secureRandomSpi = random.getSecureRandomSpi();
this.provider = random.getProvider();
if (setSeed) {
this.secureRandomSpi.engineSetSeed(seed);
}
} catch (NoSuchAlgorithmException nsae) {
// never happens, because we made sure the algorithm exists
}
}
// set algorithm if SecureRandom not subclassed (JDK 1.1 style)
if (getClass() == SecureRandom.class) {
this.algorithm = prng;
}
}
/**
204 * Creates a SecureRandom object.
205 *
206 * @param secureRandomSpi the SecureRandom implementation.
207 * @param provider the provider.
208 */
protected SecureRandom(SecureRandomSpi secureRandomSpi,
Provider provider) {
this(secureRandomSpi, provider, null);
}
private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider,
String algorithm) {
super(0);
this.secureRandomSpi = secureRandomSpi;
this.provider = provider;
this.algorithm = algorithm;
}
/**
223 * Generates a SecureRandom object that implements the specified
224 * Random Number Generator (RNG) algorithm. If the default
225 * provider package provides an implementation of the requested algorithm,
226 * an instance of SecureRandom containing that implementation is returned.
227 * If the algorithm is not available in the default
228 * package, other packages are searched.
229 *
230 *
Note that the returned instance of SecureRandom has not been seeded.
231 * A call to the setSeed method will seed the SecureRandom
232 * object. If a call is not made to setSeed, the first call
233 * to the nextBytes method will force the SecureRandom object
234 * to seed itself.
235 *
236 * @param algorithm the name of the RNG algorithm.
237 * See Appendix A in the
239 * Java Cryptography Architecture API Specification & Reference
240 * for information about standard RNG algorithm names.
241 *
242 * @return the new SecureRandom object.
243 *
244 * @exception NoSuchAlgorithmException if the RNG algorithm is
245 * not available in the caller's environment.
246 *
247 * @since 1.2
248 */
public static SecureRandom getInstance(String algorithm)
throws NoSuchAlgorithmException {
Instance instance = GetInstance.getInstance("SecureRandom",
SecureRandomSpi.class, algorithm);
return new SecureRandom((SecureRandomSpi)instance.impl,
instance.provider, algorithm);
}
/**
258 * Generates a SecureRandom object for the specified RNG
259 * algorithm, as supplied from the specified provider, if such a
260 * RNG implementation is available from the provider.
261 *
262 *
Note that the returned instance of SecureRandom has not been seeded.
263 * A call to the setSeed method will seed the SecureRandom
264 * object. If a call is not made to setSeed, the first call
265 * to the nextBytes method will force the SecureRandom object
266 * to seed itself.
267 *
268 * @param algorithm the name of the RNG algorithm.
269 * See Appendix A in the
271 * Java Cryptography Architecture API Specification & Reference
272 * for information about standard RNG algorithm names.
273 *
274 * @param provider the name of the provider.
275 *
276 * @return the new SecureRandom object.
277 *
278 * @exception NoSuchAlgorithmException if the requested RNG
279 * implementation is not available from the provider.
280 *
281 * @exception NoSuchProviderException if the provider has not been
282 * configured.
283 *
284 * @exception IllegalArgumentException if the provider name is null
285 * or empty.
286 *
287 * @see Provider
288 *
289 * @since 1.2
290 */
public static SecureRandom getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = GetInstance.getInstance("SecureRandom",
SecureRandomSpi.class, algorithm, provider);
return new SecureRandom((SecureRandomSpi)instance.impl,
instance.provider, algorithm);
}
/**
300 * Generates a SecureRandom object for the specified RNG
301 * algorithm, as supplied from the specified provider, if such a
302 * RNG implementation is available from the provider.
303 * Note: the provider doesn't have to be registered.
304 *
305 *
Note that the returned instance of SecureRandom has not been seeded.
306 * A call to the setSeed method will seed the SecureRandom
307 * object. If a call is not made to setSeed, the first call
308 * to the nextBytes method will force the SecureRandom object
309 * to seed itself.
310 *
311 * @param algorithm the name of the RNG algorithm.
312 * See Appendix A in the
314 * Java Cryptography Architecture API Specification & Reference
315 * for information about standard RNG algorithm names.
316 *
317 * @param provider the provider.
318 *
319 * @return the new SecureRandom object.
320 *
321 * @exception NoSuchAlgorithmException if the requested RNG
322 * implementation is not available from the provider.
323 *
324 * @exception IllegalArgumentException if the provider is
325 * null.
326 *
327 * @see Provider
328 *
329 * @since 1.4
330 */
public static SecureRandom getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = GetInstance.getInstance("SecureRandom",
SecureRandomSpi.class, algorithm, provider);
return new SecureRandom((SecureRandomSpi)instance.impl,
instance.provider, algorithm);
}
/**
340 * Returns the SecureRandomSpi of this SecureRandom object.
341 */
SecureRandomSpi getSecureRandomSpi() {
return secureRandomSpi;
}
/**
347 * Returns the provider of this SecureRandom object.
348 *
349 * @return the provider of this SecureRandom object.
350 */
public final Provider getProvider() {
return provider;
}
/**
356 * Returns the name of the algorithm implemented by this SecureRandom object.
357 *
358 * @return the name of the algorithm or unknown if the algorithm
359 * name cannot be determined.
360 * @since 1.5
361 */
public String getAlgorithm() {
return (algorithm != null) ? algorithm : "unknown";
}
/**
367 * Reseeds this random object. The given seed supplements, rather than
368 * replaces, the existing seed. Thus, repeated calls are guaranteed
369 * never to reduce randomness.
370 *
371 * @param seed the seed.
372 *
373 * @see #getSeed
374 */
synchronized public void setSeed(byte[] seed) {
secureRandomSpi.engineSetSeed(seed);
}
/**
80 * Reseeds this random object, using the eight bytes contained
381 * in the given long seed. The given seed supplements,
382 * rather than replaces, the existing seed. Thus, repeated calls
383 * are guaranteed never to reduce randomness.
384 *
385 *
This method is defined for compatibility with
386 * java.util.Random.
387 *
388 * @param seed the seed.
389 *
390 * @see #getSeed
391 */
public void setSeed(long seed) {
/*
394 * Ignore call from super constructor (as well as any other calls
395 * unfortunate enough to be passing 0). It's critical that we
396 * ignore call from superclass constructor, as digest has not
397 * yet been initialized at that point.
398 */
if (seed != 0) {
secureRandomSpi.engineSetSeed(longToByteArray(seed));
}
}
/**
405 * Generates a user-specified number of random bytes. This method is
406 * used as the basis of all random entities returned by this class
407 * (except seed bytes).
408 *
409 * @param bytes the array to be filled in with random bytes.
410 */
synchronized public void nextBytes(byte[] bytes) {
secureRandomSpi.engineNextBytes(bytes);
}
/**
417 * Generates an integer containing the user-specified number of
418 * pseudo-random bits (right justified, with leading zeros). This
419 * method overrides a java.util.Random method, and serves
420 * to provide a source of random bits to all of the methods inherited
421 * from that class (for example, nextInt,
422 * nextLong, and nextFloat).
423 *
424 * @param numBits number of pseudo-random bits to be generated, where
425 * 0 <= numBits <= 32.
426 *
427 * @return an int containing the user-specified number
428 * of pseudo-random bits (right justified, with leading zeros).
429 */
final protected int next(int numBits) {
int numBytes = (numBits+7)/8;
byte b[] = new byte[numBytes];
int next = 0;
nextBytes(b);
for (int i = 0; i < numBytes; i++)
next = (next << 8) + (b[i] & 0xFF);
return next >>> (numBytes*8 - numBits);
}
/**
443 * Returns the given number of seed bytes, computed using the seed
444 * generation algorithm that this class uses to seed itself. This
445 * call may be used to seed other random number generators.
446 *
447 *
This method is only included for backwards compatibility.
448 * The caller is encouraged to use one of the alternative
449 * getInstance methods to obtain a SecureRandom object, and
450 * then call the generateSeed method to obtain seed bytes
451 * from that object.
452 *
453 * @param numBytes the number of seed bytes to generate.
454 *
455 * @return the seed bytes.
456 *
457 * @see #setSeed
458 */
public static byte[] getSeed(int numBytes) {
if (seedGenerator == null)
seedGenerator = new SecureRandom();
return seedGenerator.generateSeed(numBytes);
}
/**
466 * Returns the given number of seed bytes, computed using the seed
467 * generation algorithm that this class uses to seed itself. This
468 * call may be used to seed other random number generators.
469 *
470 * @param numBytes the number of seed bytes to generate.
471 *
472 * @return the seed bytes.
473 */
public byte[] generateSeed(int numBytes) {
return secureRandomSpi.engineGenerateSeed(numBytes);
}
/**
479 * Helper function to convert a long into a byte array (least significant
480 * byte first).
481 */
private static byte[] longToByteArray(long l) {
byte[] retVal = new byte[8];
for (int i = 0; i < 8; i++) {
retVal[i] = (byte) l;
l >>= 8;
}
return retVal;
}
/**
494 * Gets a default PRNG algorithm by looking through all registered
495 * providers. Returns the first PRNG algorithm of the first provider that
496 * has registered a SecureRandom implementation, or null if none of the
497 * registered providers supplies a SecureRandom implementation.
498 */
private static String getPrngAlgorithm() {
List provs = Providers.getProviderList().providers();
for (Iterator t = provs.iterator(); t.hasNext();) {
Provider p = (Provider)t.next();
for (Iterator u = p.getServices().iterator(); u.hasNext();) {
Service s = (Service)u.next();
if (s.getType().equals("SecureRandom")) {
return s.getAlgorithm();
}
}
}
return null;
}
// Declare serialVersionUID to be compatible with JDK1.1
static final long serialVersionUID = 4940670005562187L;
// Retain unused values serialized from JDK1.1
/**
518 * @serial
519 */
private byte[] state;
/**
522 * @serial
523 */
private MessageDigest digest = null;
/**
526 * @serial
527 *
528 * We know that the MessageDigest class does not implement
529 * java.io.Serializable. However, since this field is no longer
530 * used, it will always be NULL and won't affect the serialization
531 * of the SecureRandom class itself.
532 */
private byte[] randomBytes;
/**
535 * @serial
36 */
private int randomBytesUsed;
/**
539 * @serial
540 */
private long counter;
}