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