Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/provider/SecureRandom.java
38830 views
/*1* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.provider;2627import java.io.IOException;28import java.security.MessageDigest;29import java.security.SecureRandomSpi;30import java.security.NoSuchAlgorithmException;31import java.security.NoSuchProviderException;3233/**34* <p>This class provides a crytpographically strong pseudo-random number35* generator based on the SHA-1 hash algorithm.36*37* <p>Note that if a seed is not provided, we attempt to provide sufficient38* seed bytes to completely randomize the internal state of the generator39* (20 bytes). However, our seed generation algorithm has not been thoroughly40* studied or widely deployed.41*42* <p>Also note that when a random object is deserialized,43* <a href="#engineNextBytes(byte[])">engineNextBytes</a> invoked on the44* restored random object will yield the exact same (random) bytes as the45* original object. If this behaviour is not desired, the restored random46* object should be seeded, using47* <a href="#engineSetSeed(byte[])">engineSetSeed</a>.48*49* @author Benjamin Renaud50* @author Josh Bloch51* @author Gadi Guy52*/5354public final class SecureRandom extends SecureRandomSpi55implements java.io.Serializable {5657private static final long serialVersionUID = 3581829991155417889L;5859private static final int DIGEST_SIZE = 20;60private transient MessageDigest digest;61private byte[] state;62private byte[] remainder;63private int remCount;6465/**66* This empty constructor automatically seeds the generator. We attempt67* to provide sufficient seed bytes to completely randomize the internal68* state of the generator (20 bytes). Note, however, that our seed69* generation algorithm has not been thoroughly studied or widely deployed.70*71* <p>The first time this constructor is called in a given Virtual Machine,72* it may take several seconds of CPU time to seed the generator, depending73* on the underlying hardware. Successive calls run quickly because they74* rely on the same (internal) pseudo-random number generator for their75* seed bits.76*/77public SecureRandom() {78init(null);79}8081/**82* This constructor is used to instantiate the private seeder object83* with a given seed from the SeedGenerator.84*85* @param seed the seed.86*/87private SecureRandom(byte seed[]) {88init(seed);89}9091/**92* This call, used by the constructors, instantiates the SHA digest93* and sets the seed, if given.94*/95private void init(byte[] seed) {96try {97/*98* Use the local SUN implementation to avoid native99* performance overhead.100*/101digest = MessageDigest.getInstance("SHA", "SUN");102} catch (NoSuchProviderException | NoSuchAlgorithmException e) {103// Fallback to any available.104try {105digest = MessageDigest.getInstance("SHA");106} catch (NoSuchAlgorithmException exc) {107throw new InternalError(108"internal error: SHA-1 not available.", exc);109}110}111112if (seed != null) {113engineSetSeed(seed);114}115}116117/**118* Returns the given number of seed bytes, computed using the seed119* generation algorithm that this class uses to seed itself. This120* call may be used to seed other random number generators. While121* we attempt to return a "truly random" sequence of bytes, we do not122* know exactly how random the bytes returned by this call are. (See123* the empty constructor <a href = "#SecureRandom">SecureRandom</a>124* for a brief description of the underlying algorithm.)125* The prudent user will err on the side of caution and get extra126* seed bytes, although it should be noted that seed generation is127* somewhat costly.128*129* @param numBytes the number of seed bytes to generate.130*131* @return the seed bytes.132*/133@Override134public byte[] engineGenerateSeed(int numBytes) {135// Neither of the SeedGenerator implementations require136// locking, so no sync needed here.137byte[] b = new byte[numBytes];138SeedGenerator.generateSeed(b);139return b;140}141142/**143* Reseeds this random object. The given seed supplements, rather than144* replaces, the existing seed. Thus, repeated calls are guaranteed145* never to reduce randomness.146*147* @param seed the seed.148*/149@Override150synchronized public void engineSetSeed(byte[] seed) {151if (state != null) {152digest.update(state);153for (int i = 0; i < state.length; i++) {154state[i] = 0;155}156}157state = digest.digest(seed);158}159160private static void updateState(byte[] state, byte[] output) {161int last = 1;162int v;163byte t;164boolean zf = false;165166// state(n + 1) = (state(n) + output(n) + 1) % 2^160;167for (int i = 0; i < state.length; i++) {168// Add two bytes169v = (int)state[i] + (int)output[i] + last;170// Result is lower 8 bits171t = (byte)v;172// Store result. Check for state collision.173zf = zf | (state[i] != t);174state[i] = t;175// High 8 bits are carry. Store for next iteration.176last = v >> 8;177}178179// Make sure at least one bit changes!180if (!zf) {181state[0]++;182}183}184185/**186* This static object will be seeded by SeedGenerator, and used187* to seed future instances of SHA1PRNG SecureRandoms.188*189* Bloch, Effective Java Second Edition: Item 71190*/191private static class SeederHolder {192193private static final SecureRandom seeder;194195static {196/*197* Call to SeedGenerator.generateSeed() to add additional198* seed material (likely from the Native implementation).199*/200seeder = new SecureRandom(SeedGenerator.getSystemEntropy());201byte [] b = new byte[DIGEST_SIZE];202SeedGenerator.generateSeed(b);203seeder.engineSetSeed(b);204}205}206207/**208* Generates a user-specified number of random bytes.209*210* @param bytes the array to be filled in with random bytes.211*/212@Override213public synchronized void engineNextBytes(byte[] result) {214int index = 0;215int todo;216byte[] output = remainder;217218if (state == null) {219byte[] seed = new byte[DIGEST_SIZE];220SeederHolder.seeder.engineNextBytes(seed);221state = digest.digest(seed);222}223224// Use remainder from last time225int r = remCount;226if (r > 0) {227// How many bytes?228todo = (result.length - index) < (DIGEST_SIZE - r) ?229(result.length - index) : (DIGEST_SIZE - r);230// Copy the bytes, zero the buffer231for (int i = 0; i < todo; i++) {232result[i] = output[r];233output[r++] = 0;234}235remCount += todo;236index += todo;237}238239// If we need more bytes, make them.240while (index < result.length) {241// Step the state242digest.update(state);243output = digest.digest();244updateState(state, output);245246// How many bytes?247todo = (result.length - index) > DIGEST_SIZE ?248DIGEST_SIZE : result.length - index;249// Copy the bytes, zero the buffer250for (int i = 0; i < todo; i++) {251result[index++] = output[i];252output[i] = 0;253}254remCount += todo;255}256257// Store remainder for next time258remainder = output;259remCount %= DIGEST_SIZE;260}261262/*263* readObject is called to restore the state of the random object from264* a stream. We have to create a new instance of MessageDigest, because265* it is not included in the stream (it is marked "transient").266*267* Note that the engineNextBytes() method invoked on the restored random268* object will yield the exact same (random) bytes as the original.269* If you do not want this behaviour, you should re-seed the restored270* random object, using engineSetSeed().271*/272private void readObject(java.io.ObjectInputStream s)273throws IOException, ClassNotFoundException {274275s.defaultReadObject ();276277try {278/*279* Use the local SUN implementation to avoid native280* performance overhead.281*/282digest = MessageDigest.getInstance("SHA", "SUN");283} catch (NoSuchProviderException | NoSuchAlgorithmException e) {284// Fallback to any available.285try {286digest = MessageDigest.getInstance("SHA");287} catch (NoSuchAlgorithmException exc) {288throw new InternalError(289"internal error: SHA-1 not available.", exc);290}291}292}293}294295296