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 @Override 656 public String toString() { 657 return secureRandomSpi.toString(); 658 } 659 660 /** 661 * Returns the effective {@link SecureRandomParameters} for this 662 * {@code SecureRandom} instance. 663 * <p> 664 * The returned value can be different from the 665 * {@code SecureRandomParameters} object passed into a {@code getInstance} 666 * method, but it cannot change during the lifetime of this 667 * {@code SecureRandom} object. 668 * <p> 669 * A caller can use the returned value to find out what features this 670 * {@code SecureRandom} supports. 671 * 672 * @return the effective {@link SecureRandomParameters} parameters, 673 * or {@code null} if no parameters were used. 674 * 675 * @since 9 676 * @see SecureRandomSpi 677 */ 678 public SecureRandomParameters getParameters() { 679 return secureRandomSpi.engineGetParameters(); 680 } 681 682 /** 683 * Reseeds this random object with the given seed. The seed supplements, 684 * rather than replaces, the existing seed. Thus, repeated calls are 685 * guaranteed never to reduce randomness. 686 * <p> 687 * A PRNG {@code SecureRandom} will not seed itself automatically if 688 * {@code setSeed} is called before any {@code nextBytes} or {@code reseed} 689 * calls. The caller should make sure that the {@code seed} argument 690 * contains enough entropy for the security of this {@code SecureRandom}. 691 * 692 * @param seed the seed. 693 * 694 * @see #getSeed 695 */ 696 public void setSeed(byte[] seed) { 697 if (threadSafe) { 698 secureRandomSpi.engineSetSeed(seed); 699 } else { 700 synchronized (this) { 701 secureRandomSpi.engineSetSeed(seed); 702 } 703 } 704 } 705 706 /** 707 * Reseeds this random object, using the eight bytes contained 708 * in the given {@code long seed}. The given seed supplements, 709 * rather than replaces, the existing seed. Thus, repeated calls 710 * are guaranteed never to reduce randomness. 711 * 712 * <p>This method is defined for compatibility with 713 * {@code java.util.Random}. 714 * 715 * @param seed the seed. 716 * 717 * @see #getSeed 718 */ 719 @Override 720 public void setSeed(long seed) { 721 /* 722 * Ignore call from super constructor (as well as any other calls 723 * unfortunate enough to be passing 0). It's critical that we 724 * ignore call from superclass constructor, as digest has not 725 * yet been initialized at that point. 726 */ 727 if (seed != 0) { 728 setSeed(longToByteArray(seed)); 729 } 730 } 731 732 /** 733 * Generates a user-specified number of random bytes. 734 * 735 * @param bytes the array to be filled in with random bytes. 736 */ 737 @Override 738 public void nextBytes(byte[] bytes) { 739 if (threadSafe) { 740 secureRandomSpi.engineNextBytes(bytes); 741 } else { 742 synchronized (this) { 743 secureRandomSpi.engineNextBytes(bytes); 744 } 745 } 746 } 747 748 /** 749 * Generates a user-specified number of random bytes with 750 * additional parameters. 751 * 752 * @param bytes the array to be filled in with random bytes 753 * @param params additional parameters 754 * @throws NullPointerException if {@code bytes} is null 755 * @throws UnsupportedOperationException if the underlying provider 756 * implementation has not overridden this method 757 * @throws IllegalArgumentException if {@code params} is {@code null}, 758 * illegal or unsupported by this {@code SecureRandom} 759 * 760 * @since 9 761 */ 762 public void nextBytes(byte[] bytes, SecureRandomParameters params) { 763 if (params == null) { 764 throw new IllegalArgumentException("params cannot be null"); 765 } 766 if (threadSafe) { 767 secureRandomSpi.engineNextBytes( 768 Objects.requireNonNull(bytes), params); 769 } else { 770 synchronized (this) { 771 secureRandomSpi.engineNextBytes( 772 Objects.requireNonNull(bytes), params); 773 } 774 } 775 } 776 777 /** 778 * Generates an integer containing the user-specified number of 779 * pseudo-random bits (right justified, with leading zeros). This 780 * method overrides a {@code java.util.Random} method, and serves 781 * to provide a source of random bits to all of the methods inherited 782 * from that class (for example, {@code nextInt}, 783 * {@code nextLong}, and {@code nextFloat}). 784 * 785 * @param numBits number of pseudo-random bits to be generated, where 786 * {@code 0 <= numBits <= 32}. 787 * 788 * @return an {@code int} containing the user-specified number 789 * of pseudo-random bits (right justified, with leading zeros). 790 */ 791 @Override 792 protected final int next(int numBits) { 793 int numBytes = (numBits+7)/8; 794 byte[] b = new byte[numBytes]; 795 int next = 0; 796 797 nextBytes(b); 798 for (int i = 0; i < numBytes; i++) { 799 next = (next << 8) + (b[i] & 0xFF); 800 } 801 802 return next >>> (numBytes*8 - numBits); 803 } 804 805 /** 806 * Returns the given number of seed bytes, computed using the seed 807 * generation algorithm that this class uses to seed itself. This 808 * call may be used to seed other random number generators. 809 * 810 * <p>This method is only included for backwards compatibility. 811 * The caller is encouraged to use one of the alternative 812 * {@code getInstance} methods to obtain a {@code SecureRandom} object, and 813 * then call the {@code generateSeed} method to obtain seed bytes 814 * from that object. 815 * 816 * @param numBytes the number of seed bytes to generate. 817 * 818 * @throws IllegalArgumentException if {@code numBytes} is negative 819 * @return the seed bytes. 820 * 821 * @see #setSeed 822 */ 823 public static byte[] getSeed(int numBytes) { 824 SecureRandom seedGen = seedGenerator; 825 if (seedGen == null) { 826 seedGen = new SecureRandom(); 827 seedGenerator = seedGen; 828 } 829 return seedGen.generateSeed(numBytes); 830 } 831 832 /** 833 * Returns the given number of seed bytes, computed using the seed 834 * generation algorithm that this class uses to seed itself. This 835 * call may be used to seed other random number generators. 836 * 837 * @param numBytes the number of seed bytes to generate. 838 * @throws IllegalArgumentException if {@code numBytes} is negative 839 * @return the seed bytes. 840 */ 841 public byte[] generateSeed(int numBytes) { 842 if (numBytes < 0) { 843 throw new IllegalArgumentException("numBytes cannot be negative"); 844 } 845 if (threadSafe) { 846 return secureRandomSpi.engineGenerateSeed(numBytes); 847 } else { 848 synchronized (this) { 849 return secureRandomSpi.engineGenerateSeed(numBytes); 850 } 851 } 852 } 853 854 /** 855 * Helper function to convert a long into a byte array (least significant 856 * byte first). 857 */ 858 private static byte[] longToByteArray(long l) { 859 byte[] retVal = new byte[8]; 860 861 for (int i = 0; i < 8; i++) { 862 retVal[i] = (byte) l; 863 l >>= 8; 864 } 865 866 return retVal; 867 } 868 869 /** 870 * Gets a default PRNG algorithm by looking through all registered 871 * providers. Returns the first PRNG algorithm of the first provider that 872 * has registered a {@code SecureRandom} implementation, or null if none of 873 * the registered providers supplies a {@code SecureRandom} implementation. 874 */ 875 private static String getPrngAlgorithm() { 876 for (Provider p : Providers.getProviderList().providers()) { 877 for (Service s : p.getServices()) { 878 if (s.getType().equals("SecureRandom")) { 879 return s.getAlgorithm(); 880 } 881 } 882 } 883 return null; 884 } 885 886 /* 887 * Lazily initialize since Pattern.compile() is heavy. 888 * Effective Java (2nd Edition), Item 71. 889 */ 890 private static final class StrongPatternHolder { 891 /* 892 * Entries are alg:prov separated by , 893 * Allow for prepended/appended whitespace between entries. 894 * 895 * Capture groups: 896 * 1 - alg 897 * 2 - :prov (optional) 898 * 3 - prov (optional) 899 * 4 - ,nextEntry (optional) 900 * 5 - nextEntry (optional) 901 */ 902 private static Pattern pattern = 903 Pattern.compile( 904 "\\s*([\\S&&[^:,]]*)(\\:([\\S&&[^,]]*))?\\s*(\\,(.*))?"); 905 } 906 907 /** 908 * Returns a {@code SecureRandom} object that was selected by using 909 * the algorithms/providers specified in the {@code 910 * securerandom.strongAlgorithms} {@link Security} property. 911 * <p> 912 * Some situations require strong random values, such as when 913 * creating high-value/long-lived secrets like RSA public/private 914 * keys. To help guide applications in selecting a suitable strong 915 * {@code SecureRandom} implementation, Java distributions 916 * include a list of known strong {@code SecureRandom} 917 * implementations in the {@code securerandom.strongAlgorithms} 918 * Security property. 919 * <p> 920 * Every implementation of the Java platform is required to 921 * support at least one strong {@code SecureRandom} implementation. 922 * 923 * @return a strong {@code SecureRandom} implementation as indicated 924 * by the {@code securerandom.strongAlgorithms} Security property 925 * 926 * @throws NoSuchAlgorithmException if no algorithm is available 927 * 928 * @see Security#getProperty(String) 929 * 930 * @since 1.8 931 */ 932 public static SecureRandom getInstanceStrong() 933 throws NoSuchAlgorithmException { 934 935 String property = AccessController.doPrivileged( 936 new PrivilegedAction<>() { 937 @Override 938 public String run() { 939 return Security.getProperty( 940 "securerandom.strongAlgorithms"); 941 } 942 }); 943 944 if ((property == null) || (property.length() == 0)) { 945 throw new NoSuchAlgorithmException( 946 "Null/empty securerandom.strongAlgorithms Security Property"); 947 } 948 949 String remainder = property; 950 while (remainder != null) { 951 Matcher m; 952 if ((m = StrongPatternHolder.pattern.matcher( 953 remainder)).matches()) { 954 955 String alg = m.group(1); 956 String prov = m.group(3); 957 958 try { 959 if (prov == null) { 960 return SecureRandom.getInstance(alg); 961 } else { 962 return SecureRandom.getInstance(alg, prov); 963 } 964 } catch (NoSuchAlgorithmException | 965 NoSuchProviderException e) { 966 } 967 remainder = m.group(5); 968 } else { 969 remainder = null; 970 } 971 } 972 973 throw new NoSuchAlgorithmException( 974 "No strong SecureRandom impls available: " + property); 975 } 976 977 /** 978 * Reseeds this {@code SecureRandom} with entropy input read from its 979 * entropy source. 980 * 981 * @throws UnsupportedOperationException if the underlying provider 982 * implementation has not overridden this method. 983 * 984 * @since 9 985 */ 986 public void reseed() { 987 if (threadSafe) { 988 secureRandomSpi.engineReseed(null); 989 } else { 990 synchronized (this) { 991 secureRandomSpi.engineReseed(null); 992 } 993 } 994 } 995 996 /** 997 * Reseeds this {@code SecureRandom} with entropy input read from its 998 * entropy source with additional parameters. 999 * <p> 1000 * Note that entropy is obtained from an entropy source. While 1001 * some data in {@code params} may contain entropy, its main usage is to 1002 * provide diversity. 1003 * 1004 * @param params extra parameters 1005 * @throws UnsupportedOperationException if the underlying provider 1006 * implementation has not overridden this method. 1007 * @throws IllegalArgumentException if {@code params} is {@code null}, 1008 * illegal or unsupported by this {@code SecureRandom} 1009 * 1010 * @since 9 1011 */ 1012 public void reseed(SecureRandomParameters params) { 1013 if (params == null) { 1014 throw new IllegalArgumentException("params cannot be null"); 1015 } 1016 if (threadSafe) { 1017 secureRandomSpi.engineReseed(params); 1018 } else { 1019 synchronized (this) { 1020 secureRandomSpi.engineReseed(params); 1021 } 1022 } 1023 } 1024 1025 // Declare serialVersionUID to be compatible with JDK1.1 1026 static final long serialVersionUID = 4940670005562187L; 1027 1028 // Retain unused values serialized from JDK1.1 1029 /** 1030 * @serial 1031 */ 1032 private byte[] state; 1033 /** 1034 * @serial 1035 */ 1036 private MessageDigest digest = null; 1037 /** 1038 * @serial 1039 * 1040 * We know that the MessageDigest class does not implement 1041 * java.io.Serializable. However, since this field is no longer 1042 * used, it will always be NULL and won't affect the serialization 1043 * of the {@code SecureRandom} class itself. 1044 */ 1045 private byte[] randomBytes; 1046 /** 1047 * @serial 1048 */ 1049 private int randomBytesUsed; 1050 /** 1051 * @serial 1052 */ 1053 private long counter; 1054 }