1 /* 2 * Copyright (c) 1996, 2014, 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 42 * minimally complies with the statistical random number generator tests 43 * specified in 44 * <a href="http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf"> 45 * <i>FIPS 140-2, Security Requirements for Cryptographic Modules</i></a>, 46 * section 4.9.1. 47 * Additionally, SecureRandom must produce non-deterministic output. 48 * Therefore any seed material passed to a SecureRandom object must be 49 * unpredictable, and all SecureRandom output sequences must be 50 * cryptographically strong, as described in 51 * <a href="http://tools.ietf.org/html/rfc4086"> 52 * <i>RFC 4086: Randomness Requirements for Security</i></a>. 53 * 54 * <p>A caller obtains a SecureRandom instance via the 55 * no-argument constructor or one of the {@code getInstance} methods: 56 * 57 * <pre> 58 * SecureRandom random = new SecureRandom(); 59 * </pre> 60 * 61 * <p> Many SecureRandom implementations are in the form of a pseudo-random 62 * number generator (PRNG), which means they use a deterministic algorithm 63 * to produce a pseudo-random sequence from a true random seed. 64 * Other implementations may produce true random numbers, 65 * and yet others may use a combination of both techniques. 66 * 67 * <p> Typical callers of SecureRandom invoke the following methods 68 * to retrieve random bytes: 69 * 70 * <pre> 71 * SecureRandom random = new SecureRandom(); 72 * byte bytes[] = new byte[20]; 73 * random.nextBytes(bytes); 74 * </pre> 75 * 76 * <p> Callers may also invoke the {@code generateSeed} method 77 * to generate a given number of seed bytes (to seed other random number 78 * generators, for example): 79 * <pre> 80 * byte seed[] = random.generateSeed(20); 81 * </pre> 82 * 83 * Note: Depending on the implementation, the {@code generateSeed} and 84 * {@code nextBytes} methods may block as entropy is being gathered, 85 * for example, if they need to read from /dev/random on various Unix-like 86 * operating systems. 87 * 88 * @see java.security.SecureRandomSpi 89 * @see java.util.Random 90 * 91 * @author Benjamin Renaud 92 * @author Josh Bloch 93 */ 94 95 public class SecureRandom extends java.util.Random { 96 97 private static final Debug pdebug = 98 Debug.getInstance("provider", "Provider"); 99 private static final boolean skipDebug = 100 Debug.isOn("engine=") && !Debug.isOn("securerandom"); 101 102 /** 103 * The provider. 104 * 105 * @serial 106 * @since 1.2 107 */ 108 private Provider provider = null; 109 110 /** 111 * The provider implementation. 112 * 113 * @serial 114 * @since 1.2 115 */ 116 private SecureRandomSpi secureRandomSpi = null; 117 118 /* 119 * The algorithm name of null if unknown. 120 * 121 * @serial 122 * @since 1.5 123 */ 124 private String algorithm; 125 126 // Seed Generator 127 private static volatile SecureRandom seedGenerator = null; 128 129 /** 130 * Constructs a secure random number generator (RNG) implementing the 131 * default random number algorithm. 132 * 133 * <p> This constructor traverses the list of registered security Providers, 134 * starting with the most preferred Provider. 135 * A new SecureRandom object encapsulating the 136 * SecureRandomSpi implementation from the first 137 * Provider that supports a SecureRandom (RNG) algorithm is returned. 138 * If none of the Providers support a RNG algorithm, 139 * then an implementation-specific default is returned. 140 * 141 * <p> Note that the list of registered providers may be retrieved via 142 * the {@link Security#getProviders() Security.getProviders()} method. 143 * 144 * <p> See the SecureRandom section in the <a href= 145 * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom"> 146 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 147 * for information about standard RNG algorithm names. 148 * 149 * <p> The returned SecureRandom object has not been seeded. To seed the 150 * returned object, call the {@code setSeed} method. 151 * If {@code setSeed} is not called, the first call to 152 * {@code nextBytes} will force the SecureRandom object to seed itself. 153 * This self-seeding will not occur if {@code setSeed} was 154 * previously called. 155 */ 156 public SecureRandom() { 157 /* 158 * This call to our superclass constructor will result in a call 159 * to our own {@code setSeed} method, which will return 160 * immediately when it is passed zero. 161 */ 162 super(0); 163 getDefaultPRNG(false, null); 164 } 165 166 /** 167 * Constructs a secure random number generator (RNG) implementing the 168 * default random number algorithm. 169 * The SecureRandom instance is seeded with the specified seed bytes. 170 * 171 * <p> This constructor traverses the list of registered security Providers, 172 * starting with the most preferred Provider. 173 * A new SecureRandom object encapsulating the 174 * SecureRandomSpi implementation from the first 175 * Provider that supports a SecureRandom (RNG) algorithm is returned. 176 * If none of the Providers support a RNG algorithm, 177 * then an implementation-specific default is returned. 178 * 179 * <p> Note that the list of registered providers may be retrieved via 180 * the {@link Security#getProviders() Security.getProviders()} method. 181 * 182 * <p> See the SecureRandom section in the <a href= 183 * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom"> 184 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 185 * for information about standard RNG algorithm names. 186 * 187 * @param seed the seed. 188 */ 189 public SecureRandom(byte seed[]) { 190 super(0); 191 getDefaultPRNG(true, seed); 192 } 193 194 private void getDefaultPRNG(boolean setSeed, byte[] seed) { 195 String prng = getPrngAlgorithm(); 196 if (prng == null) { 197 // bummer, get the SUN implementation 198 prng = "SHA1PRNG"; 199 this.secureRandomSpi = new sun.security.provider.SecureRandom(); 200 this.provider = Providers.getSunProvider(); 201 if (setSeed) { 202 this.secureRandomSpi.engineSetSeed(seed); 203 } 204 } else { 205 try { 206 SecureRandom random = SecureRandom.getInstance(prng); 207 this.secureRandomSpi = random.getSecureRandomSpi(); 208 this.provider = random.getProvider(); 209 if (setSeed) { 210 this.secureRandomSpi.engineSetSeed(seed); 211 } 212 } catch (NoSuchAlgorithmException nsae) { 213 // never happens, because we made sure the algorithm exists 214 throw new RuntimeException(nsae); 215 } 216 } 217 // JDK 1.1 based implementations subclass SecureRandom instead of 218 // SecureRandomSpi. They will also go through this code path because 219 // they must call a SecureRandom constructor as it is their superclass. 220 // If we are dealing with such an implementation, do not set the 221 // algorithm value as it would be inaccurate. 222 if (getClass() == SecureRandom.class) { 223 this.algorithm = prng; 224 } 225 } 226 227 /** 228 * Creates a SecureRandom object. 229 * 230 * @param secureRandomSpi the SecureRandom implementation. 231 * @param provider the provider. 232 */ 233 protected SecureRandom(SecureRandomSpi secureRandomSpi, 234 Provider provider) { 235 this(secureRandomSpi, provider, null); 236 } 237 238 private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider, 239 String algorithm) { 240 super(0); 241 this.secureRandomSpi = secureRandomSpi; 242 this.provider = provider; 243 this.algorithm = algorithm; 244 245 if (!skipDebug && pdebug != null) { 246 pdebug.println("SecureRandom." + algorithm + 247 " algorithm from: " + this.provider.getName()); 248 } 249 } 250 251 /** 252 * Returns a SecureRandom object that implements the specified 253 * Random Number Generator (RNG) algorithm. 254 * 255 * <p> This method traverses the list of registered security Providers, 256 * starting with the most preferred Provider. 257 * A new SecureRandom object encapsulating the 258 * SecureRandomSpi implementation from the first 259 * Provider that supports the specified algorithm is returned. 260 * 261 * <p> Note that the list of registered providers may be retrieved via 262 * the {@link Security#getProviders() Security.getProviders()} method. 263 * 264 * <p> The returned SecureRandom object has not been seeded. To seed the 265 * returned object, call the {@code setSeed} method. 266 * If {@code setSeed} is not called, the first call to 267 * {@code nextBytes} will force the SecureRandom object to seed itself. 268 * This self-seeding will not occur if {@code setSeed} was 269 * previously called. 270 * 271 * @param algorithm the name of the RNG algorithm. 272 * See the SecureRandom section in the <a href= 273 * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom"> 274 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 275 * for information about standard RNG algorithm names. 276 * 277 * @return the new SecureRandom object. 278 * 279 * @exception NoSuchAlgorithmException if no Provider supports a 280 * SecureRandomSpi implementation for the 281 * specified algorithm. 282 * 283 * @see Provider 284 * 285 * @since 1.2 286 */ 287 public static SecureRandom getInstance(String algorithm) 288 throws NoSuchAlgorithmException { 289 Instance instance = GetInstance.getInstance("SecureRandom", 290 SecureRandomSpi.class, algorithm); 291 return new SecureRandom((SecureRandomSpi)instance.impl, 292 instance.provider, algorithm); 293 } 294 295 /** 296 * Returns a SecureRandom object that implements the specified 297 * Random Number Generator (RNG) algorithm. 298 * 299 * <p> A new SecureRandom object encapsulating the 300 * SecureRandomSpi implementation from the specified provider 301 * is returned. The specified provider must be registered 302 * in the security provider list. 303 * 304 * <p> Note that the list of registered providers may be retrieved via 305 * the {@link Security#getProviders() Security.getProviders()} method. 306 * 307 * <p> The returned SecureRandom object has not been seeded. To seed the 308 * returned object, call the {@code setSeed} method. 309 * If {@code setSeed} is not called, the first call to 310 * {@code nextBytes} will force the SecureRandom object to seed itself. 311 * This self-seeding will not occur if {@code setSeed} was 312 * previously called. 313 * 314 * @param algorithm the name of the RNG algorithm. 315 * See the SecureRandom section in the <a href= 316 * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom"> 317 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 318 * for information about standard RNG algorithm names. 319 * 320 * @param provider the name of the provider. 321 * 322 * @return the new SecureRandom object. 323 * 324 * @exception NoSuchAlgorithmException if a SecureRandomSpi 325 * implementation for the specified algorithm is not 326 * available from the specified provider. 327 * 328 * @exception NoSuchProviderException if the specified provider is not 329 * registered in the security provider list. 330 * 331 * @exception IllegalArgumentException if the provider name is null 332 * or empty. 333 * 334 * @see Provider 335 * 336 * @since 1.2 337 */ 338 public static SecureRandom getInstance(String algorithm, String provider) 339 throws NoSuchAlgorithmException, NoSuchProviderException { 340 Instance instance = GetInstance.getInstance("SecureRandom", 341 SecureRandomSpi.class, algorithm, provider); 342 return new SecureRandom((SecureRandomSpi)instance.impl, 343 instance.provider, algorithm); 344 } 345 346 /** 347 * Returns a SecureRandom object that implements the specified 348 * Random Number Generator (RNG) algorithm. 349 * 350 * <p> A new SecureRandom object encapsulating the 351 * SecureRandomSpi implementation from the specified Provider 352 * object is returned. Note that the specified Provider object 353 * does not have to be registered in the provider list. 354 * 355 * <p> The returned SecureRandom object has not been seeded. To seed the 356 * returned object, call the {@code setSeed} method. 357 * If {@code setSeed} is not called, the first call to 358 * {@code nextBytes} will force the SecureRandom object to seed itself. 359 * This self-seeding will not occur if {@code setSeed} was 360 * previously called. 361 * 362 * @param algorithm the name of the RNG algorithm. 363 * See the SecureRandom section in the <a href= 364 * "{@docRoot}/../technotes/guides/security/StandardNames.html#SecureRandom"> 365 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 366 * for information about standard RNG algorithm names. 367 * 368 * @param provider the provider. 369 * 370 * @return the new SecureRandom object. 371 * 372 * @exception NoSuchAlgorithmException if a SecureRandomSpi 373 * implementation for the specified algorithm is not available 374 * from the specified Provider object. 375 * 376 * @exception IllegalArgumentException if the specified provider is null. 377 * 378 * @see Provider 379 * 380 * @since 1.4 381 */ 382 public static SecureRandom getInstance(String algorithm, 383 Provider provider) throws NoSuchAlgorithmException { 384 Instance instance = GetInstance.getInstance("SecureRandom", 385 SecureRandomSpi.class, algorithm, provider); 386 return new SecureRandom((SecureRandomSpi)instance.impl, 387 instance.provider, algorithm); 388 } 389 390 /** 391 * Returns the SecureRandomSpi of this SecureRandom object. 392 */ 393 SecureRandomSpi getSecureRandomSpi() { 394 return secureRandomSpi; 395 } 396 397 /** 398 * Returns the provider of this SecureRandom object. 399 * 400 * @return the provider of this SecureRandom object. 401 */ 402 public final Provider getProvider() { 403 return provider; 404 } 405 406 /** 407 * Returns the name of the algorithm implemented by this SecureRandom 408 * object. 409 * 410 * @return the name of the algorithm or {@code unknown} 411 * if the algorithm name cannot be determined. 412 * @since 1.5 413 */ 414 public String getAlgorithm() { 415 return (algorithm != null) ? algorithm : "unknown"; 416 } 417 418 /** 419 * Reseeds this random object. The given seed supplements, rather than 420 * replaces, the existing seed. Thus, repeated calls are guaranteed 421 * never to reduce randomness. 422 * 423 * @param seed the seed. 424 * 425 * @see #getSeed 426 */ 427 synchronized public void setSeed(byte[] seed) { 428 secureRandomSpi.engineSetSeed(seed); 429 } 430 431 /** 432 * Reseeds this random object, using the eight bytes contained 433 * in the given {@code long seed}. The given seed supplements, 434 * rather than replaces, the existing seed. Thus, repeated calls 435 * are guaranteed never to reduce randomness. 436 * 437 * <p>This method is defined for compatibility with 438 * {@code java.util.Random}. 439 * 440 * @param seed the seed. 441 * 442 * @see #getSeed 443 */ 444 @Override 445 public void setSeed(long seed) { 446 /* 447 * Ignore call from super constructor (as well as any other calls 448 * unfortunate enough to be passing 0). It's critical that we 449 * ignore call from superclass constructor, as digest has not 450 * yet been initialized at that point. 451 */ 452 if (seed != 0) { 453 secureRandomSpi.engineSetSeed(longToByteArray(seed)); 454 } 455 } 456 457 /** 458 * Generates a user-specified number of random bytes. 459 * 460 * <p> If a call to {@code setSeed} had not occurred previously, 461 * the first call to this method forces this SecureRandom object 462 * to seed itself. This self-seeding will not occur if 463 * {@code setSeed} was previously called. 464 * 465 * @param bytes the array to be filled in with random bytes. 466 */ 467 @Override 468 synchronized public void nextBytes(byte[] bytes) { 469 secureRandomSpi.engineNextBytes(bytes); 470 } 471 472 /** 473 * Generates an integer containing the user-specified number of 474 * pseudo-random bits (right justified, with leading zeros). This 475 * method overrides a {@code java.util.Random} method, and serves 476 * to provide a source of random bits to all of the methods inherited 477 * from that class (for example, {@code nextInt}, 478 * {@code nextLong}, and {@code nextFloat}). 479 * 480 * @param numBits number of pseudo-random bits to be generated, where 481 * {@code 0 <= numBits <= 32}. 482 * 483 * @return an {@code int} containing the user-specified number 484 * of pseudo-random bits (right justified, with leading zeros). 485 */ 486 @Override 487 final protected int next(int numBits) { 488 int numBytes = (numBits+7)/8; 489 byte b[] = new byte[numBytes]; 490 int next = 0; 491 492 nextBytes(b); 493 for (int i = 0; i < numBytes; i++) { 494 next = (next << 8) + (b[i] & 0xFF); 495 } 496 497 return next >>> (numBytes*8 - numBits); 498 } 499 500 /** 501 * Returns the given number of seed bytes, computed using the seed 502 * generation algorithm that this class uses to seed itself. This 503 * call may be used to seed other random number generators. 504 * 505 * <p>This method is only included for backwards compatibility. 506 * The caller is encouraged to use one of the alternative 507 * {@code getInstance} methods to obtain a SecureRandom object, and 508 * then call the {@code generateSeed} method to obtain seed bytes 509 * from that object. 510 * 511 * @param numBytes the number of seed bytes to generate. 512 * 513 * @return the seed bytes. 514 * 515 * @see #setSeed 516 */ 517 public static byte[] getSeed(int numBytes) { 518 if (seedGenerator == null) { 519 seedGenerator = new SecureRandom(); 520 } 521 return seedGenerator.generateSeed(numBytes); 522 } 523 524 /** 525 * Returns the given number of seed bytes, computed using the seed 526 * generation algorithm that this class uses to seed itself. This 527 * call may be used to seed other random number generators. 528 * 529 * @param numBytes the number of seed bytes to generate. 530 * 531 * @return the seed bytes. 532 */ 533 public byte[] generateSeed(int numBytes) { 534 return secureRandomSpi.engineGenerateSeed(numBytes); 535 } 536 537 /** 538 * Helper function to convert a long into a byte array (least significant 539 * byte first). 540 */ 541 private static byte[] longToByteArray(long l) { 542 byte[] retVal = new byte[8]; 543 544 for (int i = 0; i < 8; i++) { 545 retVal[i] = (byte) l; 546 l >>= 8; 547 } 548 549 return retVal; 550 } 551 552 /** 553 * Gets a default PRNG algorithm by looking through all registered 554 * providers. Returns the first PRNG algorithm of the first provider that 555 * has registered a SecureRandom implementation, or null if none of the 556 * registered providers supplies a SecureRandom implementation. 557 */ 558 private static String getPrngAlgorithm() { 559 for (Provider p : Providers.getProviderList().providers()) { 560 for (Service s : p.getServices()) { 561 if (s.getType().equals("SecureRandom")) { 562 return s.getAlgorithm(); 563 } 564 } 565 } 566 return null; 567 } 568 569 /* 570 * Lazily initialize since Pattern.compile() is heavy. 571 * Effective Java (2nd Edition), Item 71. 572 */ 573 private static final class StrongPatternHolder { 574 /* 575 * Entries are alg:prov separated by , 576 * Allow for prepended/appended whitespace between entries. 577 * 578 * Capture groups: 579 * 1 - alg 580 * 2 - :prov (optional) 581 * 3 - prov (optional) 582 * 4 - ,nextEntry (optional) 583 * 5 - nextEntry (optional) 584 */ 585 private static Pattern pattern = 586 Pattern.compile( 587 "\\s*([\\S&&[^:,]]*)(\\:([\\S&&[^,]]*))?\\s*(\\,(.*))?"); 588 } 589 590 /** 591 * Returns a {@code SecureRandom} object that was selected by using 592 * the algorithms/providers specified in the {@code 593 * securerandom.strongAlgorithms} {@link Security} property. 594 * <p> 595 * Some situations require strong random values, such as when 596 * creating high-value/long-lived secrets like RSA public/private 597 * keys. To help guide applications in selecting a suitable strong 598 * {@code SecureRandom} implementation, Java distributions 599 * include a list of known strong {@code SecureRandom} 600 * implementations in the {@code securerandom.strongAlgorithms} 601 * Security property. 602 * <p> 603 * Every implementation of the Java platform is required to 604 * support at least one strong {@code SecureRandom} implementation. 605 * 606 * @return a strong {@code SecureRandom} implementation as indicated 607 * by the {@code securerandom.strongAlgorithms} Security property 608 * 609 * @throws NoSuchAlgorithmException if no algorithm is available 610 * 611 * @see Security#getProperty(String) 612 * 613 * @since 1.8 614 */ 615 public static SecureRandom getInstanceStrong() 616 throws NoSuchAlgorithmException { 617 618 String property = AccessController.doPrivileged( 619 new PrivilegedAction<String>() { 620 @Override 621 public String run() { 622 return Security.getProperty( 623 "securerandom.strongAlgorithms"); 624 } 625 }); 626 627 if ((property == null) || (property.length() == 0)) { 628 throw new NoSuchAlgorithmException( 629 "Null/empty securerandom.strongAlgorithms Security Property"); 630 } 631 632 String remainder = property; 633 while (remainder != null) { 634 Matcher m; 635 if ((m = StrongPatternHolder.pattern.matcher( 636 remainder)).matches()) { 637 638 String alg = m.group(1); 639 String prov = m.group(3); 640 641 try { 642 if (prov == null) { 643 return SecureRandom.getInstance(alg); 644 } else { 645 return SecureRandom.getInstance(alg, prov); 646 } 647 } catch (NoSuchAlgorithmException | 648 NoSuchProviderException e) { 649 } 650 remainder = m.group(5); 651 } else { 652 remainder = null; 653 } 654 } 655 656 throw new NoSuchAlgorithmException( 657 "No strong SecureRandom impls available: " + property); 658 } 659 660 // Declare serialVersionUID to be compatible with JDK1.1 661 static final long serialVersionUID = 4940670005562187L; 662 663 // Retain unused values serialized from JDK1.1 664 /** 665 * @serial 666 */ 667 private byte[] state; 668 /** 669 * @serial 670 */ 671 private MessageDigest digest = null; 672 /** 673 * @serial 674 * 675 * We know that the MessageDigest class does not implement 676 * java.io.Serializable. However, since this field is no longer 677 * used, it will always be NULL and won't affect the serialization 678 * of the SecureRandom class itself. 679 */ 680 private byte[] randomBytes; 681 /** 682 * @serial 683 */ 684 private int randomBytesUsed; 685 /** 686 * @serial 687 */ 688 private long counter; 689 }