1/* 2 * Copyright (c) 1996, 2011, 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 26package java.security; 27 28import java.util.*; 29 30import java.security.Provider.Service; 31import java.util.function.Function; 32 33import dalvik.system.VMRuntime; 34import sun.security.jca.*; 35import sun.security.jca.GetInstance.Instance; 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 <a href="http://csrc.nist.gov/cryptval/140-2.htm"> 44 * <i>FIPS 140-2, Security Requirements for Cryptographic Modules</i></a>, 45 * section 4.9.1. 46 * Additionally, SecureRandom must produce non-deterministic output. 47 * Therefore any seed material passed to a SecureRandom object must be 48 * unpredictable, and all SecureRandom output sequences must be 49 * cryptographically strong, as described in 50 * <a href="http://www.ietf.org/rfc/rfc1750.txt"> 51 * <i>RFC 1750: Randomness Recommendations for Security</i></a>. 52 * 53 * <p>A caller obtains a SecureRandom instance via the 54 * no-argument constructor or one of the <code>getInstance</code> methods: 55 * 56 * <pre> 57 * SecureRandom random = new SecureRandom(); 58 * </pre> 59 * 60 * <p> Many SecureRandom implementations are in the form of a pseudo-random 61 * number generator (PRNG), which means they use a deterministic algorithm 62 * to produce a pseudo-random sequence from a true random seed. 63 * Other implementations may produce true random numbers, 64 * and yet others may use a combination of both techniques. 65 * 66 * <p> Typical callers of SecureRandom invoke the following methods 67 * to retrieve random bytes: 68 * 69 * <pre> 70 * SecureRandom random = new SecureRandom(); 71 * byte bytes[] = new byte[20]; 72 * random.nextBytes(bytes); 73 * </pre> 74 * 75 * <p> Callers may also invoke the <code>generateSeed</code> method 76 * to generate a given number of seed bytes (to seed other random number 77 * generators, for example): 78 * <pre> 79 * byte seed[] = random.generateSeed(20); 80 * </pre> 81 * 82 * Note: Depending on the implementation, the <code>generateSeed</code> and 83 * <code>nextBytes</code> methods may block as entropy is being gathered, 84 * for example, if they need to read from /dev/random on various unix-like 85 * operating systems. 86 * 87 * The SHA1PRNG algorithm from the Crypto provider has been deprecated as it was insecure, and also 88 * incorrectly used by some apps as a key derivation function. See 89 * <a href="http://android-developers.blogspot.com/2016/06/security-crypto-provider-deprecated-in.html"> 90 * Security "Crypto" provider deprecated in Android N</a> for details. 91 * 92 * @see java.security.SecureRandomSpi 93 * @see java.util.Random 94 * 95 * @author Benjamin Renaud 96 * @author Josh Bloch 97 */ 98 99public class SecureRandom extends java.util.Random { 100 101 /** 102 * The provider. 103 * 104 * @serial 105 * @since 1.2 106 */ 107 private Provider provider = null; 108 109 /** 110 * The provider implementation. 111 * 112 * @serial 113 * @since 1.2 114 */ 115 private SecureRandomSpi secureRandomSpi = null; 116 117 /* 118 * The algorithm name of null if unknown. 119 * 120 * @serial 121 * @since 1.5 122 */ 123 private String algorithm; 124 125 // Seed Generator 126 private static volatile SecureRandom seedGenerator = null; 127 128 /** 129 * Constructs a secure random number generator (RNG) implementing the 130 * default random number algorithm. 131 * 132 * <p> This constructor traverses the list of registered security Providers, 133 * starting with the most preferred Provider. 134 * A new SecureRandom object encapsulating the 135 * SecureRandomSpi implementation from the first 136 * Provider that supports a SecureRandom (RNG) algorithm is returned. 137 * If none of the Providers support a RNG algorithm, 138 * then an implementation-specific default is returned. 139 * 140 * <p> Note that the list of registered providers may be retrieved via 141 * the {@link Security#getProviders() Security.getProviders()} method. 142 * 143 * <p> See the SecureRandom section in the <a href= 144 * "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#SecureRandom"> 145 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 146 * for information about standard RNG algorithm names. 147 * 148 * <p> The returned SecureRandom object has not been seeded. To seed the 149 * returned object, call the <code>setSeed</code> method. 150 * If <code>setSeed</code> is not called, the first call to 151 * <code>nextBytes</code> will force the SecureRandom object to seed itself. 152 * This self-seeding will not occur if <code>setSeed</code> was 153 * previously called. 154 */ 155 public SecureRandom() { 156 /* 157 * This call to our superclass constructor will result in a call 158 * to our own <code>setSeed</code> method, which will return 159 * immediately when it is passed zero. 160 */ 161 super(0); 162 getDefaultPRNG(false, null); 163 } 164 165 /** 166 * Constructs a secure random number generator (RNG) implementing the 167 * default random number algorithm. 168 * The SecureRandom instance is seeded with the specified seed bytes. 169 * 170 * <p> This constructor traverses the list of registered security Providers, 171 * starting with the most preferred Provider. 172 * A new SecureRandom object encapsulating the 173 * SecureRandomSpi implementation from the first 174 * Provider that supports a SecureRandom (RNG) algorithm is returned. 175 * If none of the Providers support a RNG algorithm, 176 * then an implementation-specific default is returned. 177 * 178 * <p> Note that the list of registered providers may be retrieved via 179 * the {@link Security#getProviders() Security.getProviders()} method. 180 * 181 * <p> See the SecureRandom section in the <a href= 182 * "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#SecureRandom"> 183 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 184 * for information about standard RNG algorithm names. 185 * 186 * @param seed the seed. 187 */ 188 public SecureRandom(byte seed[]) { 189 super(0); 190 getDefaultPRNG(true, seed); 191 } 192 193 private void getDefaultPRNG(boolean setSeed, byte[] seed) { 194 String prng = getPrngAlgorithm(); 195 if (prng == null) { 196 // Android changed, should never happen 197 throw new IllegalStateException("No SecureRandom implementation!"); 198 } else { 199 try { 200 SecureRandom random = SecureRandom.getInstance(prng); 201 this.secureRandomSpi = random.getSecureRandomSpi(); 202 this.provider = random.getProvider(); 203 if (setSeed) { 204 this.secureRandomSpi.engineSetSeed(seed); 205 } 206 } catch (NoSuchAlgorithmException nsae) { 207 // never happens, because we made sure the algorithm exists 208 throw new RuntimeException(nsae); 209 } 210 } 211 // JDK 1.1 based implementations subclass SecureRandom instead of 212 // SecureRandomSpi. They will also go through this code path because 213 // they must call a SecureRandom constructor as it is their superclass. 214 // If we are dealing with such an implementation, do not set the 215 // algorithm value as it would be inaccurate. 216 if (getClass() == SecureRandom.class) { 217 this.algorithm = prng; 218 } 219 } 220 221 /** 222 * Creates a SecureRandom object. 223 * 224 * @param secureRandomSpi the SecureRandom implementation. 225 * @param provider the provider. 226 */ 227 protected SecureRandom(SecureRandomSpi secureRandomSpi, 228 Provider provider) { 229 this(secureRandomSpi, provider, null); 230 } 231 232 private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider, 233 String algorithm) { 234 super(0); 235 this.secureRandomSpi = secureRandomSpi; 236 this.provider = provider; 237 this.algorithm = algorithm; 238 } 239 240 /** 241 * Returns a SecureRandom object that implements the specified 242 * Random Number Generator (RNG) algorithm. 243 * 244 * <p> This method traverses the list of registered security Providers, 245 * starting with the most preferred Provider. 246 * A new SecureRandom object encapsulating the 247 * SecureRandomSpi implementation from the first 248 * Provider that supports the specified algorithm is returned. 249 * 250 * <p> Note that the list of registered providers may be retrieved via 251 * the {@link Security#getProviders() Security.getProviders()} method. 252 * 253 * <p> The returned SecureRandom object has not been seeded. To seed the 254 * returned object, call the <code>setSeed</code> method. 255 * If <code>setSeed</code> is not called, the first call to 256 * <code>nextBytes</code> will force the SecureRandom object to seed itself. 257 * This self-seeding will not occur if <code>setSeed</code> was 258 * previously called. 259 * 260 * @param algorithm the name of the RNG algorithm. 261 * See the SecureRandom section in the <a href= 262 * "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#SecureRandom"> 263 * Java Cryptography Architecture Standard Algorithm Name Documentation</a> 264 * for information about standard RNG algorithm names. 265 * 266 * @return the new SecureRandom object. 267 * 268 * @exception NoSuchAlgorithmException if no Provider supports a 269 * SecureRandomSpi implementation for the 270 * specified algorithm. 271 * 272 * @see Provider 273 * 274 * @since 1.2 275 */ 276 public static SecureRandom getInstance(String algorithm) 277 throws NoSuchAlgorithmException { 278 Instance instance = GetInstance.getInstance("SecureRandom", 279 SecureRandomSpi.class, algorithm); 280 return new SecureRandom((SecureRandomSpi)instance.impl, 281 instance.provider, algorithm); 282 } 283 284 /** 285 * Maximum SDK version for which the workaround for the Crypto provider is in place. 286 * 287 * <p> We provide instances from the Crypto provider (although the provider is not installed) to 288 * apps targeting M or earlier versions of the SDK. 289 * 290 * <p> Default is 23 (M). We have it as a field for testability and it shouldn't be changed. 291 * 292 * @hide 293 */ 294 public static final int DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND = 23; 295 296 private static int sdkTargetForCryptoProviderWorkaround = 297 DEFAULT_SDK_TARGET_FOR_CRYPTO_PROVIDER_WORKAROUND; 298 299 /** 300 * Only for testing. 301 * 302 * @hide 303 */ 304 public static void setSdkTargetForCryptoProviderWorkaround(int sdkTargetVersion) { 305 sdkTargetForCryptoProviderWorkaround = sdkTargetVersion; 306 } 307 308 /** 309 * Only for testing. 310 * 311 * @hide 312 */ 313 public static int getSdkTargetForCryptoProviderWorkaround() { 314 return sdkTargetForCryptoProviderWorkaround; 315 } 316 317 /** 318 * Returns a SecureRandom object that implements the specified 319 * Random Number Generator (RNG) algorithm. 320 * 321 * <p> A new SecureRandom object encapsulating the 322 * SecureRandomSpi implementation from the specified provider 323 * is returned. The specified provider must be registered 324 * in the security provider list. 325 * 326 * <p> Note that the list of registered providers may be retrieved via 327 * the {@link Security#getProviders() Security.getProviders()} method. 328 * 329 * <p> The returned SecureRandom object has not been seeded. To seed the 330 * returned object, call the <code>setSeed</code> method. 331 * If <code>setSeed</code> is not called, the first call to 332 * <code>nextBytes</code> will force the SecureRandom object to seed itself. 333 * This self-seeding will not occur if <code>setSeed</code> was 334 * previously called. 335 * 336 * @param algorithm the name of the RNG algorithm. 337 * See the SecureRandom section in the <a href= 338 * "{@docRoot}openjdk-redirect.html?v=8&path=/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 SecureRandom object. 345 * 346 * @exception NoSuchAlgorithmException if a SecureRandomSpi 347 * implementation for the specified algorithm is not 348 * available from the specified provider. 349 * 350 * @exception NoSuchProviderException if the specified provider is not 351 * registered in the security provider list. 352 * 353 * @exception 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 try { 363 Instance instance = GetInstance.getInstance("SecureRandom", 364 SecureRandomSpi.class, algorithm, provider); 365 return new SecureRandom((SecureRandomSpi) instance.impl, 366 instance.provider, algorithm); 367 } catch (NoSuchProviderException nspe) { 368 if ("Crypto".equals(provider)) { 369 System.logE(" ********** PLEASE READ ************ "); 370 System.logE(" * "); 371 System.logE(" * New versions of the Android SDK no longer support the Crypto provider."); 372 System.logE(" * If your app was relying on setSeed() to derive keys from strings, you"); 373 System.logE(" * should switch to using SecretKeySpec to load raw key bytes directly OR"); 374 System.logE(" * use a real key derivation function (KDF). See advice here : "); 375 System.logE(" * http://android-developers.blogspot.com/2016/06/security-crypto-provider-deprecated-in.html "); 376 System.logE(" *********************************** "); 377 if (VMRuntime.getRuntime().getTargetSdkVersion() 378 <= sdkTargetForCryptoProviderWorkaround) { 379 System.logE(" Returning an instance of SecureRandom from the Crypto provider"); 380 System.logE(" as a temporary measure so that the apps targeting earlier SDKs"); 381 System.logE(" keep working. Please do not rely on the presence of the Crypto"); 382 System.logE(" provider in the codebase, as our plan is to delete it"); 383 System.logE(" completely in the future."); 384 return getInstanceFromCryptoProvider(algorithm); 385 } 386 } 387 388 throw nspe; 389 } 390 } 391 392 private static SecureRandom getInstanceFromCryptoProvider(String algorithm) 393 throws NoSuchAlgorithmException { 394 Provider cryptoProvider; 395 try { 396 cryptoProvider = (Provider) SecureRandom.class.getClassLoader() 397 .loadClass( 398 "org.apache.harmony.security.provider.crypto.CryptoProvider") 399 .newInstance(); 400 } catch (Exception e) { 401 throw new RuntimeException(e); 402 } 403 Service service = cryptoProvider.getService("SecureRandom", algorithm); 404 Instance instance = GetInstance.getInstance(service, SecureRandomSpi.class); 405 return new SecureRandom( 406 (SecureRandomSpi) instance.impl, instance.provider, algorithm); 407 } 408 409 /** 410 * Returns a SecureRandom object that implements the specified 411 * Random Number Generator (RNG) algorithm. 412 * 413 * <p> A new SecureRandom object encapsulating the 414 * SecureRandomSpi implementation from the specified Provider 415 * object is returned. Note that the specified Provider object 416 * does not have to be registered in the provider list. 417 * 418 * <p> The returned SecureRandom object has not been seeded. To seed the 419 * returned object, call the <code>setSeed</code> method. 420 * If <code>setSeed</code> is not called, the first call to 421 * <code>nextBytes</code> will force the SecureRandom object to seed itself. 422 * This self-seeding will not occur if <code>setSeed</code> was 423 * previously called. 424 * 425 * @param algorithm the name of the RNG algorithm. 426 * See the SecureRandom section in the <a href= 427 * "{@docRoot}openjdk-redirect.html?v=8&path=/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 SecureRandom object. 434 * 435 * @exception NoSuchAlgorithmException if a SecureRandomSpi 436 * implementation for the specified algorithm is not available 437 * from the specified Provider object. 438 * 439 * @exception IllegalArgumentException if the specified provider is null. 440 * 441 * @see Provider 442 * 443 * @since 1.4 444 */ 445 public static SecureRandom getInstance(String algorithm, 446 Provider provider) throws NoSuchAlgorithmException { 447 Instance instance = GetInstance.getInstance("SecureRandom", 448 SecureRandomSpi.class, algorithm, provider); 449 return new SecureRandom((SecureRandomSpi)instance.impl, 450 instance.provider, algorithm); 451 } 452 453 /** 454 * Returns the SecureRandomSpi of this SecureRandom object. 455 */ 456 SecureRandomSpi getSecureRandomSpi() { 457 return secureRandomSpi; 458 } 459 460 /** 461 * Returns the provider of this SecureRandom object. 462 * 463 * @return the provider of this SecureRandom object. 464 */ 465 public final Provider getProvider() { 466 return provider; 467 } 468 469 /** 470 * Returns the name of the algorithm implemented by this SecureRandom 471 * object. 472 * 473 * @return the name of the algorithm or <code>unknown</code> 474 * if the algorithm name cannot be determined. 475 * @since 1.5 476 */ 477 public String getAlgorithm() { 478 return (algorithm != null) ? algorithm : "unknown"; 479 } 480 481 /** 482 * Reseeds this random object. The given seed supplements, rather than 483 * replaces, the existing seed. Thus, repeated calls are guaranteed 484 * never to reduce randomness. 485 * 486 * @param seed the seed. 487 * 488 * @see #getSeed 489 */ 490 synchronized public void setSeed(byte[] seed) { 491 secureRandomSpi.engineSetSeed(seed); 492 } 493 494 /** 495 * Reseeds this random object, using the eight bytes contained 496 * in the given <code>long seed</code>. The given seed supplements, 497 * rather than replaces, the existing seed. Thus, repeated calls 498 * are guaranteed never to reduce randomness. 499 * 500 * <p>This method is defined for compatibility with 501 * <code>java.util.Random</code>. 502 * 503 * @param seed the seed. 504 * 505 * @see #getSeed 506 */ 507 public void setSeed(long seed) { 508 /* 509 * Ignore call from super constructor (as well as any other calls 510 * unfortunate enough to be passing 0). It's critical that we 511 * ignore call from superclass constructor, as digest has not 512 * yet been initialized at that point. 513 */ 514 if (seed != 0) { 515 secureRandomSpi.engineSetSeed(longToByteArray(seed)); 516 } 517 } 518 519 /** 520 * Generates a user-specified number of random bytes. 521 * 522 * <p> If a call to <code>setSeed</code> had not occurred previously, 523 * the first call to this method forces this SecureRandom object 524 * to seed itself. This self-seeding will not occur if 525 * <code>setSeed</code> was previously called. 526 * 527 * @param bytes the array to be filled in with random bytes. 528 */ 529 530 synchronized public void nextBytes(byte[] bytes) { 531 secureRandomSpi.engineNextBytes(bytes); 532 } 533 534 /** 535 * Generates an integer containing the user-specified number of 536 * pseudo-random bits (right justified, with leading zeros). This 537 * method overrides a <code>java.util.Random</code> method, and serves 538 * to provide a source of random bits to all of the methods inherited 539 * from that class (for example, <code>nextInt</code>, 540 * <code>nextLong</code>, and <code>nextFloat</code>). 541 * 542 * @param numBits number of pseudo-random bits to be generated, where 543 * 0 <= <code>numBits</code> <= 32. 544 * 545 * @return an <code>int</code> containing the user-specified number 546 * of pseudo-random bits (right justified, with leading zeros). 547 */ 548 final protected int next(int numBits) { 549 int numBytes = (numBits+7)/8; 550 byte b[] = new byte[numBytes]; 551 int next = 0; 552 553 nextBytes(b); 554 for (int i = 0; i < numBytes; i++) 555 next = (next << 8) + (b[i] & 0xFF); 556 557 return next >>> (numBytes*8 - numBits); 558 } 559 560 /** 561 * Returns the given number of seed bytes, computed using the seed 562 * generation algorithm that this class uses to seed itself. This 563 * call may be used to seed other random number generators. 564 * 565 * <p>This method is only included for backwards compatibility. 566 * The caller is encouraged to use one of the alternative 567 * <code>getInstance</code> methods to obtain a SecureRandom object, and 568 * then call the <code>generateSeed</code> method to obtain seed bytes 569 * from that object. 570 * 571 * @param numBytes the number of seed bytes to generate. 572 * 573 * @return the seed bytes. 574 * 575 * @see #setSeed 576 */ 577 public static byte[] getSeed(int numBytes) { 578 if (seedGenerator == null) 579 seedGenerator = new SecureRandom(); 580 return seedGenerator.generateSeed(numBytes); 581 } 582 583 /** 584 * Returns the given number of seed bytes, computed using the seed 585 * generation algorithm that this class uses to seed itself. This 586 * call may be used to seed other random number generators. 587 * 588 * @param numBytes the number of seed bytes to generate. 589 * 590 * @return the seed bytes. 591 */ 592 public byte[] generateSeed(int numBytes) { 593 return secureRandomSpi.engineGenerateSeed(numBytes); 594 } 595 596 /** 597 * Helper function to convert a long into a byte array (least significant 598 * byte first). 599 */ 600 private static byte[] longToByteArray(long l) { 601 byte[] retVal = new byte[8]; 602 603 for (int i = 0; i < 8; i++) { 604 retVal[i] = (byte) l; 605 l >>= 8; 606 } 607 608 return retVal; 609 } 610 611 /** 612 * Gets a default PRNG algorithm by looking through all registered 613 * providers. Returns the first PRNG algorithm of the first provider that 614 * has registered a SecureRandom implementation, or null if none of the 615 * registered providers supplies a SecureRandom implementation. 616 */ 617 private static String getPrngAlgorithm() { 618 for (Provider p : Providers.getProviderList().providers()) { 619 for (Service s : p.getServices()) { 620 if (s.getType().equals("SecureRandom")) { 621 return s.getAlgorithm(); 622 } 623 } 624 } 625 return null; 626 } 627 628 // Declare serialVersionUID to be compatible with JDK1.1 629 static final long serialVersionUID = 4940670005562187L; 630 631 // Retain unused values serialized from JDK1.1 632 /** 633 * @serial 634 */ 635 private byte[] state; 636 /** 637 * @serial 638 */ 639 private MessageDigest digest = null; 640 /** 641 * @serial 642 * 643 * We know that the MessageDigest class does not implement 644 * java.io.Serializable. However, since this field is no longer 645 * used, it will always be NULL and won't affect the serialization 646 * of the SecureRandom class itself. 647 */ 648 private byte[] randomBytes; 649 /** 650 * @serial 651 */ 652 private int randomBytesUsed; 653 /** 654 * @serial 655 */ 656 private long counter; 657} 658