1 /*
   2  * Copyright (c) 1996, 2017, 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 java.security;
  27 
  28 import java.util.*;
  29 import java.util.regex.*;
  30 
  31 import java.security.Provider.Service;
  32 
  33 import sun.security.jca.*;
  34 import sun.security.jca.GetInstance.Instance;
  35 import sun.security.util.Debug;
  36 
  37 /**
  38  * This class provides a cryptographically strong random number
  39  * generator (RNG).
  40  *
  41  * <p>A cryptographically strong random number minimally complies with the
  42  * statistical random number generator tests specified in
  43  * <a href="http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf">
  44  * <i>FIPS 140-2, Security Requirements for Cryptographic Modules</i></a>,
  45  * section 4.9.1.
  46  * Additionally, {@code SecureRandom} must produce non-deterministic output.
  47  * Therefore any seed material passed to a {@code SecureRandom} object must be
  48  * unpredictable, and all {@code SecureRandom} output sequences must be
  49  * cryptographically strong, as described in
  50  * <a href="http://tools.ietf.org/html/rfc4086">
  51  * <i>RFC 4086: Randomness Requirements for Security</i></a>.
  52  *
  53  * <p> Many {@code SecureRandom} implementations are in the form of a
  54  * pseudo-random number generator (PRNG, also known as deterministic random
  55  * bits generator or DRBG), which means they use a deterministic algorithm
  56  * to produce a pseudo-random sequence from a random seed.
  57  * Other implementations may produce true random numbers,
  58  * and yet others may use a combination of both techniques.
  59  *
  60  * <p>A caller obtains a {@code SecureRandom} instance via the
  61  * no-argument constructor or one of the {@code getInstance} methods.
  62  * For example:
  63  *
  64  * <blockquote><pre>
  65  * SecureRandom r1 = new SecureRandom();
  66  * SecureRandom r2 = SecureRandom.getInstance("NativePRNG");
  67  * SecureRandom r3 = SecureRandom.getInstance("DRBG",
  68  *         DrbgParameters.instantiation(128, RESEED_ONLY, null));</pre>
  69  * </blockquote>
  70  *
  71  * <p> The third statement above returns a {@code SecureRandom} object of the
  72  * specific algorithm supporting the specific instantiate parameters. The
  73  * implementation's effective instantiated parameters must match this minimum
  74  * request but is not necessarily the same. For example, even if the request
  75  * does not require a certain feature, the actual instantiation can provide
  76  * the feature. An implementation may lazily instantiate a {@code SecureRandom}
  77  * until it's actually used, but the effective instantiate parameters must be
  78  * determined right after it's created and {@link #getParameters()} should
  79  * always return the same result unchanged.
  80  *
  81  * <p> Typical callers of {@code SecureRandom} invoke the following methods
  82  * to retrieve random bytes:
  83  *
  84  * <blockquote><pre>
  85  * SecureRandom random = new SecureRandom();
  86  * byte[] bytes = new byte[20];
  87  * random.nextBytes(bytes);</pre>
  88  * </blockquote>
  89  *
  90  * <p> Callers may also invoke the {@link #generateSeed} method
  91  * to generate a given number of seed bytes (to seed other random number
  92  * generators, for example):
  93  *
  94  * <blockquote><pre>
  95  * byte[] seed = random.generateSeed(20);</pre>
  96  * </blockquote>
  97  *
  98  * <p> A newly created PRNG {@code SecureRandom} object is not seeded (except
  99  * if it is created by {@link #SecureRandom(byte[])}). The first call to
 100  * {@code nextBytes} will force it to seed itself from an implementation-
 101  * specific entropy source. This self-seeding will not occur if {@code setSeed}
 102  * was previously called.
 103  *
 104  * <p> A {@code SecureRandom} can be reseeded at any time by calling the
 105  * {@code reseed} or {@code setSeed} method. The {@code reseed} method
 106  * reads entropy input from its entropy source to reseed itself.
 107  * The {@code setSeed} method requires the caller to provide the seed.
 108  *
 109  * <p> Please note that {@code reseed} may not be supported by all
 110  * {@code SecureRandom} implementations.
 111  *
 112  * <p> Some {@code SecureRandom} implementations may accept a
 113  * {@link SecureRandomParameters} parameter in its
 114  * {@link #nextBytes(byte[], SecureRandomParameters)} and
 115  * {@link #reseed(SecureRandomParameters)} methods to further
 116  * control the behavior of the methods.
 117  *
 118  * <p> Note: Depending on the implementation, the {@code generateSeed},
 119  * {@code reseed} and {@code nextBytes} methods may block as entropy is being
 120  * gathered, for example, if the entropy source is /dev/random on various
 121  * Unix-like operating systems.
 122  *
 123  * <h2> Thread safety </h2>
 124  * {@code SecureRandom} objects are safe for use by multiple concurrent threads.
 125  *
 126  * @implSpec
 127  * A {@code SecureRandom} service provider can advertise that it is thread-safe
 128  * by setting the <a href=
 129  * "{@docRoot}/../technotes/guides/security/StandardNames.html#Service">service
 130  * provider attribute</a> "ThreadSafe" to "true" when registering the provider.
 131  * Otherwise, this class will instead synchronize access to the following
 132  * methods of the {@code SecureRandomSpi} implementation:
 133  * <ul>
 134  * <li>{@link SecureRandomSpi#engineSetSeed(byte[])}
 135  * <li>{@link SecureRandomSpi#engineNextBytes(byte[])}
 136  * <li>{@link SecureRandomSpi#engineNextBytes(byte[], SecureRandomParameters)}
 137  * <li>{@link SecureRandomSpi#engineGenerateSeed(int)}
 138  * <li>{@link SecureRandomSpi#engineReseed(SecureRandomParameters)}
 139  * </ul>
 140  *
 141  * @see java.security.SecureRandomSpi
 142  * @see java.util.Random
 143  *
 144  * @author Benjamin Renaud
 145  * @author Josh Bloch
 146  */
 147 
 148 public class SecureRandom extends java.util.Random {
 149 
 150     private static final Debug pdebug =
 151                         Debug.getInstance("provider", "Provider");
 152     private static final boolean skipDebug =
 153         Debug.isOn("engine=") && !Debug.isOn("securerandom");
 154 
 155     /**
 156      * The provider.
 157      *
 158      * @serial
 159      * @since 1.2
 160      */
 161     private Provider provider = null;
 162 
 163     /**
 164      * The provider implementation.
 165      *
 166      * @serial
 167      * @since 1.2
 168      */
 169     private SecureRandomSpi secureRandomSpi = null;
 170 
 171     /**
 172      * Thread safety.
 173      *
 174      * @serial
 175      * @since 9
 176      */
 177     private final boolean threadSafe;
 178 
 179     /*
 180      * The algorithm name of null if unknown.
 181      *
 182      * @serial
 183      * @since 1.5
 184      */
 185     private String algorithm;
 186 
 187     // Seed Generator
 188     private static volatile SecureRandom seedGenerator;
 189 
 190     /**
 191      * Constructs a secure random number generator (RNG) implementing the
 192      * default random number algorithm.
 193      *
 194      * <p> This constructor traverses the list of registered security Providers,
 195      * starting with the most preferred Provider.
 196      * A new {@code SecureRandom} object encapsulating the
 197      * {@code SecureRandomSpi} implementation from the first
 198      * Provider that supports a {@code SecureRandom} (RNG) algorithm is returned.
 199      * If none of the Providers support a RNG algorithm,
 200      * then an implementation-specific default is returned.
 201      *
 202      * <p> Note that the list of registered providers may be retrieved via
 203      * the {@link Security#getProviders() Security.getProviders()} method.
 204      *
 205      * <p> See the {@code SecureRandom} section in the <a href=
 206      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 207      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 208      * for information about standard RNG algorithm names.
 209      */
 210     public SecureRandom() {
 211         /*
 212          * This call to our superclass constructor will result in a call
 213          * to our own {@code setSeed} method, which will return
 214          * immediately when it is passed zero.
 215          */
 216         super(0);
 217         getDefaultPRNG(false, null);
 218         this.threadSafe = getThreadSafe();
 219     }
 220 
 221     private boolean getThreadSafe() {
 222         if (provider == null || algorithm == null) {
 223             return false;
 224         } else {
 225             return Boolean.parseBoolean(provider.getProperty(
 226                     "SecureRandom." + algorithm + " ThreadSafe", "false"));
 227         }
 228     }
 229 
 230     /**
 231      * Constructs a secure random number generator (RNG) implementing the
 232      * default random number algorithm.
 233      * The {@code SecureRandom} instance is seeded with the specified seed bytes.
 234      *
 235      * <p> This constructor traverses the list of registered security Providers,
 236      * starting with the most preferred Provider.
 237      * A new {@code SecureRandom} object encapsulating the
 238      * {@code SecureRandomSpi} implementation from the first
 239      * Provider that supports a {@code SecureRandom} (RNG) algorithm is returned.
 240      * If none of the Providers support a RNG algorithm,
 241      * then an implementation-specific default is returned.
 242      *
 243      * <p> Note that the list of registered providers may be retrieved via
 244      * the {@link Security#getProviders() Security.getProviders()} method.
 245      *
 246      * <p> See the {@code SecureRandom} section in the <a href=
 247      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 248      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 249      * for information about standard RNG algorithm names.
 250      *
 251      * @param seed the seed.
 252      */
 253     public SecureRandom(byte[] seed) {
 254         super(0);
 255         getDefaultPRNG(true, seed);
 256         this.threadSafe = getThreadSafe();
 257     }
 258 
 259     private void getDefaultPRNG(boolean setSeed, byte[] seed) {
 260         String prng = getPrngAlgorithm();
 261         if (prng == null) {
 262             // bummer, get the SUN implementation
 263             prng = "SHA1PRNG";
 264             this.secureRandomSpi = new sun.security.provider.SecureRandom();
 265             this.provider = Providers.getSunProvider();
 266             if (setSeed) {
 267                 this.secureRandomSpi.engineSetSeed(seed);
 268             }
 269         } else {
 270             try {
 271                 SecureRandom random = SecureRandom.getInstance(prng);
 272                 this.secureRandomSpi = random.getSecureRandomSpi();
 273                 this.provider = random.getProvider();
 274                 if (setSeed) {
 275                     this.secureRandomSpi.engineSetSeed(seed);
 276                 }
 277             } catch (NoSuchAlgorithmException nsae) {
 278                 // never happens, because we made sure the algorithm exists
 279                 throw new RuntimeException(nsae);
 280             }
 281         }
 282         // JDK 1.1 based implementations subclass SecureRandom instead of
 283         // SecureRandomSpi. They will also go through this code path because
 284         // they must call a SecureRandom constructor as it is their superclass.
 285         // If we are dealing with such an implementation, do not set the
 286         // algorithm value as it would be inaccurate.
 287         if (getClass() == SecureRandom.class) {
 288             this.algorithm = prng;
 289         }
 290     }
 291 
 292     /**
 293      * Creates a {@code SecureRandom} object.
 294      *
 295      * @param secureRandomSpi the {@code SecureRandom} implementation.
 296      * @param provider the provider.
 297      */
 298     protected SecureRandom(SecureRandomSpi secureRandomSpi,
 299                            Provider provider) {
 300         this(secureRandomSpi, provider, null);
 301     }
 302 
 303     private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider,
 304             String algorithm) {
 305         super(0);
 306         this.secureRandomSpi = secureRandomSpi;
 307         this.provider = provider;
 308         this.algorithm = algorithm;
 309         this.threadSafe = getThreadSafe();
 310 
 311         if (!skipDebug && pdebug != null) {
 312             pdebug.println("SecureRandom." + algorithm +
 313                 " algorithm from: " + getProviderName());
 314         }
 315     }
 316 
 317     private String getProviderName() {
 318         return (provider == null) ? "(no provider)" : provider.getName();
 319     }
 320 
 321     /**
 322      * Returns a {@code SecureRandom} object that implements the specified
 323      * Random Number Generator (RNG) algorithm.
 324      *
 325      * <p> This method traverses the list of registered security Providers,
 326      * starting with the most preferred Provider.
 327      * A new {@code SecureRandom} object encapsulating the
 328      * {@code SecureRandomSpi} implementation from the first
 329      * Provider that supports the specified algorithm is returned.
 330      *
 331      * <p> Note that the list of registered providers may be retrieved via
 332      * the {@link Security#getProviders() Security.getProviders()} method.
 333      *
 334      * @implNote
 335      * The JDK Reference Implementation additionally uses the
 336      * {@code jdk.security.provider.preferred}
 337      * {@link Security#getProperty(String) Security} property to determine
 338      * the preferred provider order for the specified algorithm. This
 339      * may be different than the order of providers returned by
 340      * {@link Security#getProviders() Security.getProviders()}.
 341      *
 342      * @param algorithm the name of the RNG algorithm.
 343      * See the {@code SecureRandom} section in the <a href=
 344      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 345      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 346      * for information about standard RNG algorithm names.
 347      *
 348      * @return the new {@code SecureRandom} object
 349      *
 350      * @throws NoSuchAlgorithmException if no {@code Provider} supports a
 351      *         {@code SecureRandomSpi} implementation for the
 352      *         specified algorithm
 353      *
 354      * @throws NullPointerException if {@code algorithm} is {@code null}
 355      *
 356      * @see Provider
 357      *
 358      * @since 1.2
 359      */
 360     public static SecureRandom getInstance(String algorithm)
 361             throws NoSuchAlgorithmException {
 362         Objects.requireNonNull(algorithm, "null algorithm name");
 363         Instance instance = GetInstance.getInstance("SecureRandom",
 364                 SecureRandomSpi.class, algorithm);
 365         return new SecureRandom((SecureRandomSpi)instance.impl,
 366                 instance.provider, algorithm);
 367     }
 368 
 369     /**
 370      * Returns a {@code SecureRandom} object that implements the specified
 371      * Random Number Generator (RNG) algorithm.
 372      *
 373      * <p> A new {@code SecureRandom} object encapsulating the
 374      * {@code SecureRandomSpi} implementation from the specified provider
 375      * is returned.  The specified provider must be registered
 376      * in the security provider list.
 377      *
 378      * <p> Note that the list of registered providers may be retrieved via
 379      * the {@link Security#getProviders() Security.getProviders()} method.
 380      *
 381      * @param algorithm the name of the RNG algorithm.
 382      * See the {@code SecureRandom} section in the <a href=
 383      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 384      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 385      * for information about standard RNG algorithm names.
 386      *
 387      * @param provider the name of the provider.
 388      *
 389      * @return the new {@code SecureRandom} object
 390      *
 391      * @throws IllegalArgumentException if the provider name is {@code null}
 392      *         or empty
 393      *
 394      * @throws NoSuchAlgorithmException if a {@code SecureRandomSpi}
 395      *         implementation for the specified algorithm is not
 396      *         available from the specified provider
 397      *
 398      * @throws NoSuchProviderException if the specified provider is not
 399      *         registered in the security provider list
 400      *
 401      * @throws NullPointerException if {@code algorithm} is {@code null}
 402      *
 403      * @see Provider
 404      *
 405      * @since 1.2
 406      */
 407     public static SecureRandom getInstance(String algorithm, String provider)
 408             throws NoSuchAlgorithmException, NoSuchProviderException {
 409         Objects.requireNonNull(algorithm, "null algorithm name");
 410         Instance instance = GetInstance.getInstance("SecureRandom",
 411             SecureRandomSpi.class, algorithm, provider);
 412         return new SecureRandom((SecureRandomSpi)instance.impl,
 413             instance.provider, algorithm);
 414     }
 415 
 416     /**
 417      * Returns a {@code SecureRandom} object that implements the specified
 418      * Random Number Generator (RNG) algorithm.
 419      *
 420      * <p> A new {@code SecureRandom} object encapsulating the
 421      * {@code SecureRandomSpi} implementation from the specified {@code Provider}
 422      * object is returned.  Note that the specified {@code Provider} object
 423      * does not have to be registered in the provider list.
 424      *
 425      * @param algorithm the name of the RNG algorithm.
 426      * See the {@code SecureRandom} section in the <a href=
 427      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 428      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 429      * for information about standard RNG algorithm names.
 430      *
 431      * @param provider the provider.
 432      *
 433      * @return the new {@code SecureRandom} object
 434      *
 435      * @throws IllegalArgumentException if the specified provider is
 436      *         {@code null}
 437      *
 438      * @throws NoSuchAlgorithmException if a {@code SecureRandomSpi}
 439      *         implementation for the specified algorithm is not available
 440      *         from the specified {@code Provider} object
 441      *
 442      * @throws NullPointerException if {@code algorithm} is {@code null}
 443      *
 444      * @see Provider
 445      *
 446      * @since 1.4
 447      */
 448     public static SecureRandom getInstance(String algorithm,
 449             Provider provider) throws NoSuchAlgorithmException {
 450         Objects.requireNonNull(algorithm, "null algorithm name");
 451         Instance instance = GetInstance.getInstance("SecureRandom",
 452             SecureRandomSpi.class, algorithm, provider);
 453         return new SecureRandom((SecureRandomSpi)instance.impl,
 454             instance.provider, algorithm);
 455     }
 456 
 457     /**
 458      * Returns a {@code SecureRandom} object that implements the specified
 459      * Random Number Generator (RNG) algorithm and supports the specified
 460      * {@code SecureRandomParameters} request.
 461      *
 462      * <p> This method traverses the list of registered security Providers,
 463      * starting with the most preferred Provider.
 464      * A new {@code SecureRandom} object encapsulating the
 465      * {@code SecureRandomSpi} implementation from the first
 466      * Provider that supports the specified algorithm and the specified
 467      * {@code SecureRandomParameters} is returned.
 468      *
 469      * <p> Note that the list of registered providers may be retrieved via
 470      * the {@link Security#getProviders() Security.getProviders()} method.
 471      *
 472      * @implNote
 473      * The JDK Reference Implementation additionally uses the
 474      * {@code jdk.security.provider.preferred} property to determine
 475      * the preferred provider order for the specified algorithm. This
 476      * may be different than the order of providers returned by
 477      * {@link Security#getProviders() Security.getProviders()}.
 478      *
 479      * @param algorithm the name of the RNG algorithm.
 480      * See the {@code SecureRandom} section in the <a href=
 481      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 482      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 483      * for information about standard RNG algorithm names.
 484      *
 485      * @param params the {@code SecureRandomParameters}
 486      *               the newly created {@code SecureRandom} object must support.
 487      *
 488      * @return the new {@code SecureRandom} object
 489      *
 490      * @throws IllegalArgumentException if the specified params is
 491      *         {@code null}
 492      *
 493      * @throws NoSuchAlgorithmException if no Provider supports a
 494      *         {@code SecureRandomSpi} implementation for the specified
 495      *         algorithm and parameters
 496      *
 497      * @throws NullPointerException if {@code algorithm} is {@code null}
 498      *
 499      * @see Provider
 500      *
 501      * @since 9
 502      */
 503     public static SecureRandom getInstance(
 504             String algorithm, SecureRandomParameters params)
 505             throws NoSuchAlgorithmException {
 506         Objects.requireNonNull(algorithm, "null algorithm name");
 507         if (params == null) {
 508             throw new IllegalArgumentException("params cannot be null");
 509         }
 510         Instance instance = GetInstance.getInstance("SecureRandom",
 511                 SecureRandomSpi.class, algorithm, params);
 512         return new SecureRandom((SecureRandomSpi)instance.impl,
 513                 instance.provider, algorithm);
 514     }
 515 
 516     /**
 517      * Returns a {@code SecureRandom} object that implements the specified
 518      * Random Number Generator (RNG) algorithm and supports the specified
 519      * {@code SecureRandomParameters} request.
 520      *
 521      * <p> A new {@code SecureRandom} object encapsulating the
 522      * {@code SecureRandomSpi} implementation from the specified provider
 523      * is returned.  The specified provider must be registered
 524      * in the security provider list.
 525      *
 526      * <p> Note that the list of registered providers may be retrieved via
 527      * the {@link Security#getProviders() Security.getProviders()} method.
 528      *
 529      * @param algorithm the name of the RNG algorithm.
 530      * See the {@code SecureRandom} section in the <a href=
 531      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 532      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 533      * for information about standard RNG algorithm names.
 534      *
 535      * @param params the {@code SecureRandomParameters}
 536      *               the newly created {@code SecureRandom} object must support.
 537      *
 538      * @param provider the name of the provider.
 539      *
 540      * @return the new {@code SecureRandom} object
 541      *
 542      * @throws IllegalArgumentException if the provider name is {@code null}
 543      *         or empty, or params is {@code null}
 544      *
 545      * @throws NoSuchAlgorithmException if the specified provider does not
 546      *         support a {@code SecureRandomSpi} implementation for the
 547      *         specified algorithm and parameters
 548      *
 549      * @throws NoSuchProviderException if the specified provider is not
 550      *         registered in the security provider list
 551      *
 552      * @throws NullPointerException if {@code algorithm} is {@code null}
 553      *
 554      * @see Provider
 555      *
 556      * @since 9
 557      */
 558     public static SecureRandom getInstance(String algorithm,
 559             SecureRandomParameters params, String provider)
 560             throws NoSuchAlgorithmException, NoSuchProviderException {
 561         Objects.requireNonNull(algorithm, "null algorithm name");
 562         if (params == null) {
 563             throw new IllegalArgumentException("params cannot be null");
 564         }
 565         Instance instance = GetInstance.getInstance("SecureRandom",
 566                 SecureRandomSpi.class, algorithm, params, provider);
 567         return new SecureRandom((SecureRandomSpi)instance.impl,
 568                 instance.provider, algorithm);
 569     }
 570 
 571     /**
 572      * Returns a {@code SecureRandom} object that implements the specified
 573      * Random Number Generator (RNG) algorithm and supports the specified
 574      * {@code SecureRandomParameters} request.
 575      *
 576      * <p> A new {@code SecureRandom} object encapsulating the
 577      * {@code SecureRandomSpi} implementation from the specified
 578      * {@code Provider} object is returned.  Note that the specified
 579      * {@code Provider} object does not have to be registered in the
 580      * provider list.
 581      *
 582      * @param algorithm the name of the RNG algorithm.
 583      * See the {@code SecureRandom} section in the <a href=
 584      * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom">
 585      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
 586      * for information about standard RNG algorithm names.
 587      *
 588      * @param params the {@code SecureRandomParameters}
 589      *               the newly created {@code SecureRandom} object must support.
 590      *
 591      * @param provider the provider.
 592      *
 593      * @return the new {@code SecureRandom} object
 594      *
 595      * @throws IllegalArgumentException if the specified provider or params
 596      *         is {@code null}
 597      *
 598      * @throws NoSuchAlgorithmException if the specified provider does not
 599      *         support a {@code SecureRandomSpi} implementation for the
 600      *         specified algorithm and parameters
 601      *
 602      * @throws NullPointerException if {@code algorithm} is {@code null}
 603      *
 604      * @see Provider
 605      *
 606      * @since 9
 607      */
 608     public static SecureRandom getInstance(String algorithm,
 609             SecureRandomParameters params, Provider provider)
 610             throws NoSuchAlgorithmException {
 611         Objects.requireNonNull(algorithm, "null algorithm name");
 612         if (params == null) {
 613             throw new IllegalArgumentException("params cannot be null");
 614         }
 615         Instance instance = GetInstance.getInstance("SecureRandom",
 616                 SecureRandomSpi.class, algorithm, params, provider);
 617         return new SecureRandom((SecureRandomSpi)instance.impl,
 618                 instance.provider, algorithm);
 619     }
 620 
 621     /**
 622      * Returns the {@code SecureRandomSpi} of this {@code SecureRandom} object.
 623      */
 624     SecureRandomSpi getSecureRandomSpi() {
 625         return secureRandomSpi;
 626     }
 627 
 628     /**
 629      * Returns the provider of this {@code SecureRandom} object.
 630      *
 631      * @return the provider of this {@code SecureRandom} object.
 632      */
 633     public final Provider getProvider() {
 634         return provider;
 635     }
 636 
 637     /**
 638      * Returns the name of the algorithm implemented by this
 639      * {@code SecureRandom} object.
 640      *
 641      * @return the name of the algorithm or {@code unknown}
 642      *          if the algorithm name cannot be determined.
 643      * @since 1.5
 644      */
 645     public String getAlgorithm() {
 646         return Objects.toString(algorithm, "unknown");
 647     }
 648 
 649     /**
 650      * Returns a Human-readable string representation of this
 651      * {@code SecureRandom}.
 652      *
 653      * @return the string representation
 654      *
 655      * @since 9
 656      */
 657     @Override
 658     public String toString() {
 659         return secureRandomSpi.toString();
 660     }
 661 
 662     /**
 663      * Returns the effective {@link SecureRandomParameters} for this
 664      * {@code SecureRandom} instance.
 665      * <p>
 666      * The returned value can be different from the
 667      * {@code SecureRandomParameters} object passed into a {@code getInstance}
 668      * method, but it cannot change during the lifetime of this
 669      * {@code SecureRandom} object.
 670      * <p>
 671      * A caller can use the returned value to find out what features this
 672      * {@code SecureRandom} supports.
 673      *
 674      * @return the effective {@link SecureRandomParameters} parameters,
 675      * or {@code null} if no parameters were used.
 676      *
 677      * @since 9
 678      * @see SecureRandomSpi
 679      */
 680     public SecureRandomParameters getParameters() {
 681         return secureRandomSpi.engineGetParameters();
 682     }
 683 
 684     /**
 685      * Reseeds this random object with the given seed. The seed supplements,
 686      * rather than replaces, the existing seed. Thus, repeated calls are
 687      * guaranteed never to reduce randomness.
 688      * <p>
 689      * A PRNG {@code SecureRandom} will not seed itself automatically if
 690      * {@code setSeed} is called before any {@code nextBytes} or {@code reseed}
 691      * calls. The caller should make sure that the {@code seed} argument
 692      * contains enough entropy for the security of this {@code SecureRandom}.
 693      *
 694      * @param seed the seed.
 695      *
 696      * @see #getSeed
 697      */
 698     public void setSeed(byte[] seed) {
 699         if (threadSafe) {
 700             secureRandomSpi.engineSetSeed(seed);
 701         } else {
 702             synchronized (this) {
 703                 secureRandomSpi.engineSetSeed(seed);
 704             }
 705         }
 706     }
 707 
 708     /**
 709      * Reseeds this random object, using the eight bytes contained
 710      * in the given {@code long seed}. The given seed supplements,
 711      * rather than replaces, the existing seed. Thus, repeated calls
 712      * are guaranteed never to reduce randomness.
 713      *
 714      * <p>This method is defined for compatibility with
 715      * {@code java.util.Random}.
 716      *
 717      * @param seed the seed.
 718      *
 719      * @see #getSeed
 720      */
 721     @Override
 722     public void setSeed(long seed) {
 723         /*
 724          * Ignore call from super constructor (as well as any other calls
 725          * unfortunate enough to be passing 0).  It's critical that we
 726          * ignore call from superclass constructor, as digest has not
 727          * yet been initialized at that point.
 728          */
 729         if (seed != 0) {
 730             setSeed(longToByteArray(seed));
 731         }
 732     }
 733 
 734     /**
 735      * Generates a user-specified number of random bytes.
 736      *
 737      * @param bytes the array to be filled in with random bytes.
 738      */
 739     @Override
 740     public void nextBytes(byte[] bytes) {
 741         if (threadSafe) {
 742             secureRandomSpi.engineNextBytes(bytes);
 743         } else {
 744             synchronized (this) {
 745                 secureRandomSpi.engineNextBytes(bytes);
 746             }
 747         }
 748     }
 749 
 750     /**
 751      * Generates a user-specified number of random bytes with
 752      * additional parameters.
 753      *
 754      * @param bytes the array to be filled in with random bytes
 755      * @param params additional parameters
 756      * @throws NullPointerException if {@code bytes} is null
 757      * @throws UnsupportedOperationException if the underlying provider
 758      *         implementation has not overridden this method
 759      * @throws IllegalArgumentException if {@code params} is {@code null},
 760      *         illegal or unsupported by this {@code SecureRandom}
 761      *
 762      * @since 9
 763      */
 764     public void nextBytes(byte[] bytes, SecureRandomParameters params) {
 765         if (params == null) {
 766             throw new IllegalArgumentException("params cannot be null");
 767         }
 768         if (threadSafe) {
 769             secureRandomSpi.engineNextBytes(
 770                     Objects.requireNonNull(bytes), params);
 771         } else {
 772             synchronized (this) {
 773                 secureRandomSpi.engineNextBytes(
 774                         Objects.requireNonNull(bytes), params);
 775             }
 776         }
 777     }
 778 
 779     /**
 780      * Generates an integer containing the user-specified number of
 781      * pseudo-random bits (right justified, with leading zeros).  This
 782      * method overrides a {@code java.util.Random} method, and serves
 783      * to provide a source of random bits to all of the methods inherited
 784      * from that class (for example, {@code nextInt},
 785      * {@code nextLong}, and {@code nextFloat}).
 786      *
 787      * @param numBits number of pseudo-random bits to be generated, where
 788      * {@code 0 <= numBits <= 32}.
 789      *
 790      * @return an {@code int} containing the user-specified number
 791      * of pseudo-random bits (right justified, with leading zeros).
 792      */
 793     @Override
 794     protected final int next(int numBits) {
 795         int numBytes = (numBits+7)/8;
 796         byte[] b = new byte[numBytes];
 797         int next = 0;
 798 
 799         nextBytes(b);
 800         for (int i = 0; i < numBytes; i++) {
 801             next = (next << 8) + (b[i] & 0xFF);
 802         }
 803 
 804         return next >>> (numBytes*8 - numBits);
 805     }
 806 
 807     /**
 808      * Returns the given number of seed bytes, computed using the seed
 809      * generation algorithm that this class uses to seed itself.  This
 810      * call may be used to seed other random number generators.
 811      *
 812      * <p>This method is only included for backwards compatibility.
 813      * The caller is encouraged to use one of the alternative
 814      * {@code getInstance} methods to obtain a {@code SecureRandom} object, and
 815      * then call the {@code generateSeed} method to obtain seed bytes
 816      * from that object.
 817      *
 818      * @param numBytes the number of seed bytes to generate.
 819      *
 820      * @throws IllegalArgumentException if {@code numBytes} is negative
 821      * @return the seed bytes.
 822      *
 823      * @see #setSeed
 824      */
 825     public static byte[] getSeed(int numBytes) {
 826         SecureRandom seedGen = seedGenerator;
 827         if (seedGen == null) {
 828             seedGen = new SecureRandom();
 829             seedGenerator = seedGen;
 830         }
 831         return seedGen.generateSeed(numBytes);
 832     }
 833 
 834     /**
 835      * Returns the given number of seed bytes, computed using the seed
 836      * generation algorithm that this class uses to seed itself.  This
 837      * call may be used to seed other random number generators.
 838      *
 839      * @param numBytes the number of seed bytes to generate.
 840      * @throws IllegalArgumentException if {@code numBytes} is negative
 841      * @return the seed bytes.
 842      */
 843     public byte[] generateSeed(int numBytes) {
 844         if (numBytes < 0) {
 845             throw new IllegalArgumentException("numBytes cannot be negative");
 846         }
 847         if (threadSafe) {
 848             return secureRandomSpi.engineGenerateSeed(numBytes);
 849         } else {
 850             synchronized (this) {
 851                 return secureRandomSpi.engineGenerateSeed(numBytes);
 852             }
 853         }
 854     }
 855 
 856     /**
 857      * Helper function to convert a long into a byte array (least significant
 858      * byte first).
 859      */
 860     private static byte[] longToByteArray(long l) {
 861         byte[] retVal = new byte[8];
 862 
 863         for (int i = 0; i < 8; i++) {
 864             retVal[i] = (byte) l;
 865             l >>= 8;
 866         }
 867 
 868         return retVal;
 869     }
 870 
 871     /**
 872      * Gets a default PRNG algorithm by looking through all registered
 873      * providers. Returns the first PRNG algorithm of the first provider that
 874      * has registered a {@code SecureRandom} implementation, or null if none of
 875      * the registered providers supplies a {@code SecureRandom} implementation.
 876      */
 877     private static String getPrngAlgorithm() {
 878         for (Provider p : Providers.getProviderList().providers()) {
 879             for (Service s : p.getServices()) {
 880                 if (s.getType().equals("SecureRandom")) {
 881                     return s.getAlgorithm();
 882                 }
 883             }
 884         }
 885         return null;
 886     }
 887 
 888     /*
 889      * Lazily initialize since Pattern.compile() is heavy.
 890      * Effective Java (2nd Edition), Item 71.
 891      */
 892     private static final class StrongPatternHolder {
 893         /*
 894          * Entries are alg:prov separated by ,
 895          * Allow for prepended/appended whitespace between entries.
 896          *
 897          * Capture groups:
 898          *     1 - alg
 899          *     2 - :prov (optional)
 900          *     3 - prov (optional)
 901          *     4 - ,nextEntry (optional)
 902          *     5 - nextEntry (optional)
 903          */
 904         private static Pattern pattern =
 905             Pattern.compile(
 906                 "\\s*([\\S&&[^:,]]*)(\\:([\\S&&[^,]]*))?\\s*(\\,(.*))?");
 907     }
 908 
 909     /**
 910      * Returns a {@code SecureRandom} object that was selected by using
 911      * the algorithms/providers specified in the {@code
 912      * securerandom.strongAlgorithms} {@link Security} property.
 913      * <p>
 914      * Some situations require strong random values, such as when
 915      * creating high-value/long-lived secrets like RSA public/private
 916      * keys.  To help guide applications in selecting a suitable strong
 917      * {@code SecureRandom} implementation, Java distributions
 918      * include a list of known strong {@code SecureRandom}
 919      * implementations in the {@code securerandom.strongAlgorithms}
 920      * Security property.
 921      * <p>
 922      * Every implementation of the Java platform is required to
 923      * support at least one strong {@code SecureRandom} implementation.
 924      *
 925      * @return a strong {@code SecureRandom} implementation as indicated
 926      * by the {@code securerandom.strongAlgorithms} Security property
 927      *
 928      * @throws NoSuchAlgorithmException if no algorithm is available
 929      *
 930      * @see Security#getProperty(String)
 931      *
 932      * @since 1.8
 933      */
 934     public static SecureRandom getInstanceStrong()
 935             throws NoSuchAlgorithmException {
 936 
 937         String property = AccessController.doPrivileged(
 938             new PrivilegedAction<>() {
 939                 @Override
 940                 public String run() {
 941                     return Security.getProperty(
 942                         "securerandom.strongAlgorithms");
 943                 }
 944             });
 945 
 946         if ((property == null) || (property.length() == 0)) {
 947             throw new NoSuchAlgorithmException(
 948                 "Null/empty securerandom.strongAlgorithms Security Property");
 949         }
 950 
 951         String remainder = property;
 952         while (remainder != null) {
 953             Matcher m;
 954             if ((m = StrongPatternHolder.pattern.matcher(
 955                     remainder)).matches()) {
 956 
 957                 String alg = m.group(1);
 958                 String prov = m.group(3);
 959 
 960                 try {
 961                     if (prov == null) {
 962                         return SecureRandom.getInstance(alg);
 963                     } else {
 964                         return SecureRandom.getInstance(alg, prov);
 965                     }
 966                 } catch (NoSuchAlgorithmException |
 967                         NoSuchProviderException e) {
 968                 }
 969                 remainder = m.group(5);
 970             } else {
 971                 remainder = null;
 972             }
 973         }
 974 
 975         throw new NoSuchAlgorithmException(
 976             "No strong SecureRandom impls available: " + property);
 977     }
 978 
 979     /**
 980      * Reseeds this {@code SecureRandom} with entropy input read from its
 981      * entropy source.
 982      *
 983      * @throws UnsupportedOperationException if the underlying provider
 984      *         implementation has not overridden this method.
 985      *
 986      * @since 9
 987      */
 988     public void reseed() {
 989         if (threadSafe) {
 990             secureRandomSpi.engineReseed(null);
 991         } else {
 992             synchronized (this) {
 993                 secureRandomSpi.engineReseed(null);
 994             }
 995         }
 996     }
 997 
 998     /**
 999      * Reseeds this {@code SecureRandom} with entropy input read from its
1000      * entropy source with additional parameters.
1001      * <p>
1002      * Note that entropy is obtained from an entropy source. While
1003      * some data in {@code params} may contain entropy, its main usage is to
1004      * provide diversity.
1005      *
1006      * @param params extra parameters
1007      * @throws UnsupportedOperationException if the underlying provider
1008      *         implementation has not overridden this method.
1009      * @throws IllegalArgumentException if {@code params} is {@code null},
1010      *         illegal or unsupported by this {@code SecureRandom}
1011      *
1012      * @since 9
1013      */
1014     public void reseed(SecureRandomParameters params) {
1015         if (params == null) {
1016             throw new IllegalArgumentException("params cannot be null");
1017         }
1018         if (threadSafe) {
1019             secureRandomSpi.engineReseed(params);
1020         } else {
1021             synchronized (this) {
1022                 secureRandomSpi.engineReseed(params);
1023             }
1024         }
1025     }
1026 
1027     // Declare serialVersionUID to be compatible with JDK1.1
1028     static final long serialVersionUID = 4940670005562187L;
1029 
1030     // Retain unused values serialized from JDK1.1
1031     /**
1032      * @serial
1033      */
1034     private byte[] state;
1035     /**
1036      * @serial
1037      */
1038     private MessageDigest digest = null;
1039     /**
1040      * @serial
1041      *
1042      * We know that the MessageDigest class does not implement
1043      * java.io.Serializable.  However, since this field is no longer
1044      * used, it will always be NULL and won't affect the serialization
1045      * of the {@code SecureRandom} class itself.
1046      */
1047     private byte[] randomBytes;
1048     /**
1049      * @serial
1050      */
1051     private int randomBytesUsed;
1052     /**
1053      * @serial
1054      */
1055     private long counter;
1056 }