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