0N/A/*
3909N/A * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.security;
0N/A
0N/Aimport java.util.*;
0N/A
0N/Aimport java.security.Provider.Service;
0N/A
0N/Aimport sun.security.jca.*;
0N/Aimport sun.security.jca.GetInstance.Instance;
0N/A
0N/A/**
0N/A * This class provides a cryptographically strong random number
0N/A * generator (RNG).
0N/A *
0N/A * <p>A cryptographically strong random number
0N/A * minimally complies with the statistical random number generator tests
0N/A * specified in <a href="http://csrc.nist.gov/cryptval/140-2.htm">
0N/A * <i>FIPS 140-2, Security Requirements for Cryptographic Modules</i></a>,
0N/A * section 4.9.1.
0N/A * Additionally, SecureRandom must produce non-deterministic output.
0N/A * Therefore any seed material passed to a SecureRandom object must be
0N/A * unpredictable, and all SecureRandom output sequences must be
0N/A * cryptographically strong, as described in
0N/A * <a href="http://www.ietf.org/rfc/rfc1750.txt">
0N/A * <i>RFC 1750: Randomness Recommendations for Security</i></a>.
0N/A *
0N/A * <p>A caller obtains a SecureRandom instance via the
0N/A * no-argument constructor or one of the <code>getInstance</code> methods:
0N/A *
0N/A * <pre>
0N/A * SecureRandom random = new SecureRandom();
0N/A * </pre>
0N/A *
0N/A * <p> Many SecureRandom implementations are in the form of a pseudo-random
0N/A * number generator (PRNG), which means they use a deterministic algorithm
0N/A * to produce a pseudo-random sequence from a true random seed.
0N/A * Other implementations may produce true random numbers,
0N/A * and yet others may use a combination of both techniques.
0N/A *
0N/A * <p> Typical callers of SecureRandom invoke the following methods
0N/A * to retrieve random bytes:
0N/A *
0N/A * <pre>
0N/A * SecureRandom random = new SecureRandom();
0N/A * byte bytes[] = new byte[20];
0N/A * random.nextBytes(bytes);
0N/A * </pre>
0N/A *
0N/A * <p> Callers may also invoke the <code>generateSeed</code> method
0N/A * to generate a given number of seed bytes (to seed other random number
0N/A * generators, for example):
0N/A * <pre>
0N/A * byte seed[] = random.generateSeed(20);
0N/A * </pre>
0N/A *
0N/A * Note: Depending on the implementation, the <code>generateSeed</code> and
0N/A * <code>nextBytes</code> methods may block as entropy is being gathered,
0N/A * for example, if they need to read from /dev/random on various unix-like
0N/A * operating systems.
0N/A *
0N/A * @see java.security.SecureRandomSpi
0N/A * @see java.util.Random
0N/A *
0N/A * @author Benjamin Renaud
0N/A * @author Josh Bloch
0N/A */
0N/A
0N/Apublic class SecureRandom extends java.util.Random {
0N/A
0N/A /**
0N/A * The provider.
0N/A *
0N/A * @serial
0N/A * @since 1.2
0N/A */
0N/A private Provider provider = null;
0N/A
0N/A /**
0N/A * The provider implementation.
0N/A *
0N/A * @serial
0N/A * @since 1.2
0N/A */
0N/A private SecureRandomSpi secureRandomSpi = null;
0N/A
0N/A /*
0N/A * The algorithm name of null if unknown.
0N/A *
0N/A * @serial
0N/A * @since 1.5
0N/A */
0N/A private String algorithm;
0N/A
0N/A // Seed Generator
0N/A private static volatile SecureRandom seedGenerator = null;
0N/A
0N/A /**
0N/A * Constructs a secure random number generator (RNG) implementing the
0N/A * default random number algorithm.
0N/A *
0N/A * <p> This constructor traverses the list of registered security Providers,
0N/A * starting with the most preferred Provider.
0N/A * A new SecureRandom object encapsulating the
0N/A * SecureRandomSpi implementation from the first
0N/A * Provider that supports a SecureRandom (RNG) algorithm is returned.
0N/A * If none of the Providers support a RNG algorithm,
0N/A * then an implementation-specific default is returned.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
3465N/A * <p> See the SecureRandom section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard RNG algorithm names.
0N/A *
0N/A * <p> The returned SecureRandom object has not been seeded. To seed the
0N/A * returned object, call the <code>setSeed</code> method.
0N/A * If <code>setSeed</code> is not called, the first call to
0N/A * <code>nextBytes</code> will force the SecureRandom object to seed itself.
0N/A * This self-seeding will not occur if <code>setSeed</code> was
0N/A * previously called.
0N/A */
0N/A public SecureRandom() {
0N/A /*
0N/A * This call to our superclass constructor will result in a call
0N/A * to our own <code>setSeed</code> method, which will return
0N/A * immediately when it is passed zero.
0N/A */
0N/A super(0);
0N/A getDefaultPRNG(false, null);
0N/A }
0N/A
0N/A /**
0N/A * Constructs a secure random number generator (RNG) implementing the
0N/A * default random number algorithm.
0N/A * The SecureRandom instance is seeded with the specified seed bytes.
0N/A *
0N/A * <p> This constructor traverses the list of registered security Providers,
0N/A * starting with the most preferred Provider.
0N/A * A new SecureRandom object encapsulating the
0N/A * SecureRandomSpi implementation from the first
0N/A * Provider that supports a SecureRandom (RNG) algorithm is returned.
0N/A * If none of the Providers support a RNG algorithm,
0N/A * then an implementation-specific default is returned.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
3465N/A * <p> See the SecureRandom section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard RNG algorithm names.
0N/A *
0N/A * @param seed the seed.
0N/A */
0N/A public SecureRandom(byte seed[]) {
0N/A super(0);
0N/A getDefaultPRNG(true, seed);
0N/A }
0N/A
0N/A private void getDefaultPRNG(boolean setSeed, byte[] seed) {
0N/A String prng = getPrngAlgorithm();
0N/A if (prng == null) {
0N/A // bummer, get the SUN implementation
0N/A prng = "SHA1PRNG";
0N/A this.secureRandomSpi = new sun.security.provider.SecureRandom();
0N/A this.provider = Providers.getSunProvider();
0N/A if (setSeed) {
0N/A this.secureRandomSpi.engineSetSeed(seed);
0N/A }
0N/A } else {
0N/A try {
0N/A SecureRandom random = SecureRandom.getInstance(prng);
0N/A this.secureRandomSpi = random.getSecureRandomSpi();
0N/A this.provider = random.getProvider();
0N/A if (setSeed) {
0N/A this.secureRandomSpi.engineSetSeed(seed);
0N/A }
0N/A } catch (NoSuchAlgorithmException nsae) {
0N/A // never happens, because we made sure the algorithm exists
0N/A throw new RuntimeException(nsae);
0N/A }
0N/A }
0N/A // JDK 1.1 based implementations subclass SecureRandom instead of
0N/A // SecureRandomSpi. They will also go through this code path because
0N/A // they must call a SecureRandom constructor as it is their superclass.
0N/A // If we are dealing with such an implementation, do not set the
0N/A // algorithm value as it would be inaccurate.
0N/A if (getClass() == SecureRandom.class) {
0N/A this.algorithm = prng;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Creates a SecureRandom object.
0N/A *
0N/A * @param secureRandomSpi the SecureRandom implementation.
0N/A * @param provider the provider.
0N/A */
0N/A protected SecureRandom(SecureRandomSpi secureRandomSpi,
0N/A Provider provider) {
0N/A this(secureRandomSpi, provider, null);
0N/A }
0N/A
0N/A private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider,
0N/A String algorithm) {
0N/A super(0);
0N/A this.secureRandomSpi = secureRandomSpi;
0N/A this.provider = provider;
0N/A this.algorithm = algorithm;
0N/A }
0N/A
0N/A /**
0N/A * Returns a SecureRandom object that implements the specified
0N/A * Random Number Generator (RNG) algorithm.
0N/A *
0N/A * <p> This method traverses the list of registered security Providers,
0N/A * starting with the most preferred Provider.
0N/A * A new SecureRandom object encapsulating the
0N/A * SecureRandomSpi implementation from the first
0N/A * Provider that supports the specified algorithm is returned.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * <p> The returned SecureRandom object has not been seeded. To seed the
0N/A * returned object, call the <code>setSeed</code> method.
0N/A * If <code>setSeed</code> is not called, the first call to
0N/A * <code>nextBytes</code> will force the SecureRandom object to seed itself.
0N/A * This self-seeding will not occur if <code>setSeed</code> was
0N/A * previously called.
0N/A *
0N/A * @param algorithm the name of the RNG algorithm.
3465N/A * See the SecureRandom section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard RNG algorithm names.
0N/A *
0N/A * @return the new SecureRandom object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if no Provider supports a
0N/A * SecureRandomSpi implementation for the
0N/A * specified algorithm.
0N/A *
0N/A * @see Provider
0N/A *
0N/A * @since 1.2
0N/A */
0N/A public static SecureRandom getInstance(String algorithm)
0N/A throws NoSuchAlgorithmException {
0N/A Instance instance = GetInstance.getInstance("SecureRandom",
0N/A SecureRandomSpi.class, algorithm);
0N/A return new SecureRandom((SecureRandomSpi)instance.impl,
0N/A instance.provider, algorithm);
0N/A }
0N/A
0N/A /**
0N/A * Returns a SecureRandom object that implements the specified
0N/A * Random Number Generator (RNG) algorithm.
0N/A *
0N/A * <p> A new SecureRandom object encapsulating the
0N/A * SecureRandomSpi implementation from the specified provider
0N/A * is returned. The specified provider must be registered
0N/A * in the security provider list.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * <p> The returned SecureRandom object has not been seeded. To seed the
0N/A * returned object, call the <code>setSeed</code> method.
0N/A * If <code>setSeed</code> is not called, the first call to
0N/A * <code>nextBytes</code> will force the SecureRandom object to seed itself.
0N/A * This self-seeding will not occur if <code>setSeed</code> was
0N/A * previously called.
0N/A *
0N/A * @param algorithm the name of the RNG algorithm.
3465N/A * See the SecureRandom section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard RNG algorithm names.
0N/A *
0N/A * @param provider the name of the provider.
0N/A *
0N/A * @return the new SecureRandom object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a SecureRandomSpi
0N/A * implementation for the specified algorithm is not
0N/A * available from the specified provider.
0N/A *
0N/A * @exception NoSuchProviderException if the specified provider is not
0N/A * registered in the security provider list.
0N/A *
0N/A * @exception IllegalArgumentException if the provider name is null
0N/A * or empty.
0N/A *
0N/A * @see Provider
0N/A *
0N/A * @since 1.2
0N/A */
0N/A public static SecureRandom getInstance(String algorithm, String provider)
0N/A throws NoSuchAlgorithmException, NoSuchProviderException {
0N/A Instance instance = GetInstance.getInstance("SecureRandom",
0N/A SecureRandomSpi.class, algorithm, provider);
0N/A return new SecureRandom((SecureRandomSpi)instance.impl,
0N/A instance.provider, algorithm);
0N/A }
0N/A
0N/A /**
0N/A * Returns a SecureRandom object that implements the specified
0N/A * Random Number Generator (RNG) algorithm.
0N/A *
0N/A * <p> A new SecureRandom object encapsulating the
0N/A * SecureRandomSpi implementation from the specified Provider
0N/A * object is returned. Note that the specified Provider object
0N/A * does not have to be registered in the provider list.
0N/A *
0N/A * <p> The returned SecureRandom object has not been seeded. To seed the
0N/A * returned object, call the <code>setSeed</code> method.
0N/A * If <code>setSeed</code> is not called, the first call to
0N/A * <code>nextBytes</code> will force the SecureRandom object to seed itself.
0N/A * This self-seeding will not occur if <code>setSeed</code> was
0N/A * previously called.
0N/A *
0N/A * @param algorithm the name of the RNG algorithm.
3465N/A * See the SecureRandom section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard RNG algorithm names.
0N/A *
0N/A * @param provider the provider.
0N/A *
0N/A * @return the new SecureRandom object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a SecureRandomSpi
0N/A * implementation for the specified algorithm is not available
0N/A * from the specified Provider object.
0N/A *
0N/A * @exception IllegalArgumentException if the specified provider is null.
0N/A *
0N/A * @see Provider
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public static SecureRandom getInstance(String algorithm,
0N/A Provider provider) throws NoSuchAlgorithmException {
0N/A Instance instance = GetInstance.getInstance("SecureRandom",
0N/A SecureRandomSpi.class, algorithm, provider);
0N/A return new SecureRandom((SecureRandomSpi)instance.impl,
0N/A instance.provider, algorithm);
0N/A }
0N/A
0N/A /**
0N/A * Returns the SecureRandomSpi of this SecureRandom object.
0N/A */
0N/A SecureRandomSpi getSecureRandomSpi() {
0N/A return secureRandomSpi;
0N/A }
0N/A
0N/A /**
0N/A * Returns the provider of this SecureRandom object.
0N/A *
0N/A * @return the provider of this SecureRandom object.
0N/A */
0N/A public final Provider getProvider() {
0N/A return provider;
0N/A }
0N/A
0N/A /**
0N/A * Returns the name of the algorithm implemented by this SecureRandom
0N/A * object.
0N/A *
0N/A * @return the name of the algorithm or <code>unknown</code>
0N/A * if the algorithm name cannot be determined.
0N/A * @since 1.5
0N/A */
0N/A public String getAlgorithm() {
0N/A return (algorithm != null) ? algorithm : "unknown";
0N/A }
0N/A
0N/A /**
0N/A * Reseeds this random object. The given seed supplements, rather than
0N/A * replaces, the existing seed. Thus, repeated calls are guaranteed
0N/A * never to reduce randomness.
0N/A *
0N/A * @param seed the seed.
0N/A *
0N/A * @see #getSeed
0N/A */
0N/A synchronized public void setSeed(byte[] seed) {
0N/A secureRandomSpi.engineSetSeed(seed);
0N/A }
0N/A
0N/A /**
0N/A * Reseeds this random object, using the eight bytes contained
0N/A * in the given <code>long seed</code>. The given seed supplements,
0N/A * rather than replaces, the existing seed. Thus, repeated calls
0N/A * are guaranteed never to reduce randomness.
0N/A *
0N/A * <p>This method is defined for compatibility with
0N/A * <code>java.util.Random</code>.
0N/A *
0N/A * @param seed the seed.
0N/A *
0N/A * @see #getSeed
0N/A */
0N/A public void setSeed(long seed) {
0N/A /*
0N/A * Ignore call from super constructor (as well as any other calls
0N/A * unfortunate enough to be passing 0). It's critical that we
0N/A * ignore call from superclass constructor, as digest has not
0N/A * yet been initialized at that point.
0N/A */
0N/A if (seed != 0) {
0N/A secureRandomSpi.engineSetSeed(longToByteArray(seed));
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Generates a user-specified number of random bytes.
0N/A *
0N/A * <p> If a call to <code>setSeed</code> had not occurred previously,
0N/A * the first call to this method forces this SecureRandom object
0N/A * to seed itself. This self-seeding will not occur if
0N/A * <code>setSeed</code> was previously called.
0N/A *
0N/A * @param bytes the array to be filled in with random bytes.
0N/A */
0N/A
0N/A synchronized public void nextBytes(byte[] bytes) {
0N/A secureRandomSpi.engineNextBytes(bytes);
0N/A }
0N/A
0N/A /**
0N/A * Generates an integer containing the user-specified number of
0N/A * pseudo-random bits (right justified, with leading zeros). This
0N/A * method overrides a <code>java.util.Random</code> method, and serves
0N/A * to provide a source of random bits to all of the methods inherited
0N/A * from that class (for example, <code>nextInt</code>,
0N/A * <code>nextLong</code>, and <code>nextFloat</code>).
0N/A *
0N/A * @param numBits number of pseudo-random bits to be generated, where
0N/A * 0 <= <code>numBits</code> <= 32.
0N/A *
0N/A * @return an <code>int</code> containing the user-specified number
0N/A * of pseudo-random bits (right justified, with leading zeros).
0N/A */
0N/A final protected int next(int numBits) {
0N/A int numBytes = (numBits+7)/8;
0N/A byte b[] = new byte[numBytes];
0N/A int next = 0;
0N/A
0N/A nextBytes(b);
0N/A for (int i = 0; i < numBytes; i++)
0N/A next = (next << 8) + (b[i] & 0xFF);
0N/A
0N/A return next >>> (numBytes*8 - numBits);
0N/A }
0N/A
0N/A /**
0N/A * Returns the given number of seed bytes, computed using the seed
0N/A * generation algorithm that this class uses to seed itself. This
0N/A * call may be used to seed other random number generators.
0N/A *
0N/A * <p>This method is only included for backwards compatibility.
0N/A * The caller is encouraged to use one of the alternative
0N/A * <code>getInstance</code> methods to obtain a SecureRandom object, and
0N/A * then call the <code>generateSeed</code> method to obtain seed bytes
0N/A * from that object.
0N/A *
0N/A * @param numBytes the number of seed bytes to generate.
0N/A *
0N/A * @return the seed bytes.
0N/A *
0N/A * @see #setSeed
0N/A */
0N/A public static byte[] getSeed(int numBytes) {
0N/A if (seedGenerator == null)
0N/A seedGenerator = new SecureRandom();
0N/A return seedGenerator.generateSeed(numBytes);
0N/A }
0N/A
0N/A /**
0N/A * Returns the given number of seed bytes, computed using the seed
0N/A * generation algorithm that this class uses to seed itself. This
0N/A * call may be used to seed other random number generators.
0N/A *
0N/A * @param numBytes the number of seed bytes to generate.
0N/A *
0N/A * @return the seed bytes.
0N/A */
0N/A public byte[] generateSeed(int numBytes) {
0N/A return secureRandomSpi.engineGenerateSeed(numBytes);
0N/A }
0N/A
0N/A /**
0N/A * Helper function to convert a long into a byte array (least significant
0N/A * byte first).
0N/A */
0N/A private static byte[] longToByteArray(long l) {
0N/A byte[] retVal = new byte[8];
0N/A
0N/A for (int i = 0; i < 8; i++) {
0N/A retVal[i] = (byte) l;
0N/A l >>= 8;
0N/A }
0N/A
0N/A return retVal;
0N/A }
0N/A
0N/A /**
0N/A * Gets a default PRNG algorithm by looking through all registered
0N/A * providers. Returns the first PRNG algorithm of the first provider that
0N/A * has registered a SecureRandom implementation, or null if none of the
0N/A * registered providers supplies a SecureRandom implementation.
0N/A */
0N/A private static String getPrngAlgorithm() {
0N/A for (Provider p : Providers.getProviderList().providers()) {
0N/A for (Service s : p.getServices()) {
0N/A if (s.getType().equals("SecureRandom")) {
0N/A return s.getAlgorithm();
0N/A }
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A // Declare serialVersionUID to be compatible with JDK1.1
0N/A static final long serialVersionUID = 4940670005562187L;
0N/A
0N/A // Retain unused values serialized from JDK1.1
0N/A /**
0N/A * @serial
0N/A */
0N/A private byte[] state;
0N/A /**
0N/A * @serial
0N/A */
0N/A private MessageDigest digest = null;
0N/A /**
0N/A * @serial
0N/A *
0N/A * We know that the MessageDigest class does not implement
0N/A * java.io.Serializable. However, since this field is no longer
0N/A * used, it will always be NULL and won't affect the serialization
0N/A * of the SecureRandom class itself.
0N/A */
0N/A private byte[] randomBytes;
0N/A /**
0N/A * @serial
0N/A */
0N/A private int randomBytesUsed;
0N/A /**
0N/A * @serial
0N/A */
0N/A private long counter;
0N/A}