001: /*
002: * @(#)SecureRandom.java 1.17 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package sun.security.provider;
029:
030: import java.io.IOException;
031: import java.security.MessageDigest;
032: import java.security.SecureRandomSpi;
033: import java.security.NoSuchAlgorithmException;
034:
035: /**
036: * <p>This class provides a crytpographically strong pseudo-random number
037: * generator based on the SHA-1 hash algorithm.
038: *
039: * <p>Note that if a seed is not provided, we attempt to provide sufficient
040: * seed bytes to completely randomize the internal state of the generator
041: * (20 bytes). However, our seed generation algorithm has not been thoroughly
042: * studied or widely deployed.
043: *
044: * <p>Also note that when a random object is deserialized,
045: * <a href="#engineNextBytes(byte[])">engineNextBytes</a> invoked on the
046: * restored random object will yield the exact same (random) bytes as the
047: * original object. If this behaviour is not desired, the restored random
048: * object should be seeded, using
049: * <a href="#engineSetSeed(byte[])">engineSetSeed</a>.
050: *
051: * @version 1.10, 02/02/00
052: * @author Benjamin Renaud
053: * @author Josh Bloch
054: * @author Gadi Guy
055: */
056:
057: public final class SecureRandom extends SecureRandomSpi implements
058: java.io.Serializable {
059:
060: /**
061: * This static object will be seeded by SeedGenerator, and used
062: * to seed future instances of SecureRandom
063: */
064: private static SecureRandom seeder;
065:
066: private static final int DIGEST_SIZE = 20;
067: private transient MessageDigest digest;
068: private byte[] state;
069: private byte[] remainder;
070: private int remCount;
071:
072: /**
073: * This empty constructor automatically seeds the generator. We attempt
074: * to provide sufficient seed bytes to completely randomize the internal
075: * state of the generator (20 bytes). Note, however, that our seed
076: * generation algorithm has not been thoroughly studied or widely deployed.
077: *
078: * <p>The first time this constructor is called in a given Virtual Machine,
079: * it may take several seconds of CPU time to seed the generator, depending
080: * on the underlying hardware. Successive calls run quickly because they
081: * rely on the same (internal) pseudo-random number generator for their
082: * seed bits.
083: */
084: public SecureRandom() {
085: init(null);
086: }
087:
088: /**
089: * This constructor is used to instatiate the private seeder object
090: * with a given seed from the SeedGenerator.
091: *
092: * @param seed the seed.
093: */
094: private SecureRandom(byte seed[]) {
095: init(seed);
096: }
097:
098: /**
099: * This call, used by the constructors, instantiates the SHA digest
100: * and sets the seed, if given.
101: */
102: private void init(byte[] seed) {
103: try {
104: digest = MessageDigest.getInstance("SHA");
105: } catch (NoSuchAlgorithmException e) {
106: throw new InternalError(
107: "internal error: SHA-1 not available.");
108: }
109:
110: if (seed != null) {
111: engineSetSeed(seed);
112: }
113: }
114:
115: /**
116: * Returns the given number of seed bytes, computed using the seed
117: * generation algorithm that this class uses to seed itself. This
118: * call may be used to seed other random number generators. While
119: * we attempt to return a "truly random" sequence of bytes, we do not
120: * know exactly how random the bytes returned by this call are. (See
121: * the empty constructor <a href = "#SecureRandom">SecureRandom</a>
122: * for a brief description of the underlying algorithm.)
123: * The prudent user will err on the side of caution and get extra
124: * seed bytes, although it should be noted that seed generation is
125: * somewhat costly.
126: *
127: * @param numBytes the number of seed bytes to generate.
128: *
129: * @return the seed bytes.
130: */
131: public byte[] engineGenerateSeed(int numBytes) {
132: byte[] b = new byte[numBytes];
133: SeedGenerator.generateSeed(b);
134: return b;
135: }
136:
137: /**
138: * Reseeds this random object. The given seed supplements, rather than
139: * replaces, the existing seed. Thus, repeated calls are guaranteed
140: * never to reduce randomness.
141: *
142: * @param seed the seed.
143: */
144: synchronized public void engineSetSeed(byte[] seed) {
145: if (state != null) {
146: digest.update(state);
147: for (int i = 0; i < state.length; i++)
148: state[i] = 0;
149: }
150: state = digest.digest(seed);
151: }
152:
153: private static void updateState(byte[] state, byte[] output) {
154: int last = 1;
155: int v = 0;
156: byte t = 0;
157: boolean zf = false;
158:
159: // state(n + 1) = (state(n) + output(n) + 1) % 2^160;
160: for (int i = 0; i < state.length; i++) {
161: // Add two bytes
162: v = (int) state[i] + (int) output[i] + last;
163: // Result is lower 8 bits
164: t = (byte) v;
165: // Store result. Check for state collision.
166: zf = zf | (state[i] != t);
167: state[i] = t;
168: // High 8 bits are carry. Store for next iteration.
169: last = v >> 8;
170: }
171:
172: // Make sure at least one bit changes!
173: if (!zf)
174: state[0]++;
175: }
176:
177: /**
178: * Generates a user-specified number of random bytes.
179: *
180: * @param bytes the array to be filled in with random bytes.
181: */
182: public synchronized void engineNextBytes(byte[] result) {
183: int index = 0;
184: int todo;
185: byte[] output = remainder;
186:
187: if (state == null) {
188: if (seeder == null) {
189: seeder = new SecureRandom(SeedGenerator
190: .getSystemEntropy());
191: seeder.engineSetSeed(engineGenerateSeed(DIGEST_SIZE));
192: }
193:
194: byte[] seed = new byte[DIGEST_SIZE];
195: seeder.engineNextBytes(seed);
196: state = digest.digest(seed);
197: }
198:
199: // Use remainder from last time
200: int r = remCount;
201: if (r > 0) {
202: // How many bytes?
203: todo = (result.length - index) < (DIGEST_SIZE - r) ? (result.length - index)
204: : (DIGEST_SIZE - r);
205: // Copy the bytes, zero the buffer
206: for (int i = 0; i < todo; i++) {
207: result[i] = output[r];
208: output[r++] = 0;
209: }
210: remCount += todo;
211: index += todo;
212: }
213:
214: // If we need more bytes, make them.
215: while (index < result.length) {
216: // Step the state
217: digest.update(state);
218: output = digest.digest();
219: updateState(state, output);
220:
221: // How many bytes?
222: todo = (result.length - index) > DIGEST_SIZE ? DIGEST_SIZE
223: : result.length - index;
224: // Copy the bytes, zero the buffer
225: for (int i = 0; i < todo; i++) {
226: result[index++] = output[i];
227: output[i] = 0;
228: }
229: remCount += todo;
230: }
231:
232: // Store remainder for next time
233: remainder = output;
234: remCount %= DIGEST_SIZE;
235: }
236:
237: /*
238: * readObject is called to restore the state of the random object from
239: * a stream. We have to create a new instance of MessageDigest, because
240: * it is not included in the stream (it is marked "transient").
241: *
242: * Note that the engineNextBytes() method invoked on the restored random
243: * object will yield the exact same (random) bytes as the original.
244: * If you do not want this behaviour, you should re-seed the restored
245: * random object, using engineSetSeed().
246: */
247: private void readObject(java.io.ObjectInputStream s)
248: throws IOException, ClassNotFoundException {
249:
250: s.defaultReadObject();
251:
252: try {
253: digest = MessageDigest.getInstance("SHA");
254: } catch (NoSuchAlgorithmException e) {
255: throw new InternalError(
256: "internal error: SHA-1 not available.");
257: }
258: }
259: }
|