3
import org.bouncycastle.crypto.digests.SHA1Digest;
6
* An implementation of SecureRandom specifically for the
7
* light-weight API, JDK 1.0, and the J2ME. Random generation is
8
* based on the traditional SHA1 with counter. Calling setSeed
9
* will always increase the entropy of the hash.
11
public class SecureRandom
12
extends java.util.Random
14
private static SecureRandom rand = new SecureRandom();
18
private long counter = 1;
19
private SHA1Digest digest = new SHA1Digest();
20
private byte[] state = new byte[digest.getDigestSize()];
22
// public constructors
26
setSeed(System.currentTimeMillis());
36
// protected constructors
37
// protected SecureRandom(SecureRandomSpi srs, Provider provider);
39
// public class methods
40
public static SecureRandom getInstance(String algorithm)
42
return new SecureRandom();
45
public static SecureRandom getInstance(String algorithm, String provider)
47
return new SecureRandom();
50
public static byte[] getSeed(
53
byte[] rv = new byte[numBytes];
55
rand.setSeed(System.currentTimeMillis());
61
// public instance methods
62
public byte[] generateSeed(
65
byte[] rv = new byte[numBytes];
72
// public final Provider getProvider();
76
digest.update(inSeed, 0, inSeed.length);
79
// public methods overriding random
80
public void nextBytes(
85
digest.doFinal(state, 0);
87
for (int i = 0; i != bytes.length; i++)
89
if (stateOff == state.length)
91
byte[] b = longToBytes(counter++);
93
digest.update(b, 0, b.length);
94
digest.update(state, 0, state.length);
95
digest.doFinal(state, 0);
98
bytes[i] = state[stateOff++];
101
byte[] b = longToBytes(counter++);
103
digest.update(b, 0, b.length);
104
digest.update(state, 0, state.length);
112
setSeed(longToBytes(rSeed));
116
private byte[] intBytes = new byte[4];
124
for (int i = 0; i < 4; i++)
126
result = (result << 8) + (intBytes[i] & 0xff);
132
protected final int next(
135
int size = (numBits + 7) / 8;
136
byte[] bytes = new byte[size];
142
for (int i = 0; i < size; i++)
144
result = (result << 8) + (bytes[i] & 0xff);
147
return result & ((1 << numBits) - 1);
150
private byte[] longBytes = new byte[8];
152
private byte[] longToBytes(
155
for (int i = 0; i != 8; i++)
157
longBytes[i] = (byte)val;