我正在开发一个可能变得非常强大的Web应用程序,它需要大量的随机数来表示cookie值,salt值,共享会话标识符和其他类似大小(~20字节)的项目。通常需要随机数来响应用户活动(例如注册,登录,付款等)。由于这种活动的时间是不可预测的,我的前提是尝试使用它来向java.security.SecureRandom添加熵。对象,以加快它。
我开发了一个类,它使用随机数生成器的每第10次调用的当前系统时间的最后8位来向随机数生成器添加熵。我的问题是:这种策略是否会提供比仅使用默认播种的SecureRandom更高的性能。
请参阅下面的代码,看看我到底是怎么做的。提前感谢您的任何反馈。
import java.security.SecureRandom;
/**
* Uses the lowest 8 bits of the time at which the call to get random bytes
* is made to seed a SecureRandom object to generate more randomness.
* This class can speed up the random number generator if: Each call to
* nextBytes is of a limited length;
* and the time at which nextBytes is called is unpredictable because it
* is being done in response to user activity.
*
*/
public class SRandFactory {
private static final int BITLEN = 8;
private static final int BITMASK = 0xFF;
private static final int LONGLEN = 64;
private static final int INTERVAL = 10;
private static SecureRandom sr = new SecureRandom();
private static long nextSeed = 0L;
private static int callCount = 0;
private static int shiftBits = 0;
private static void seedUp() {
if (callCount++ >= INTERVAL) {
callCount = 0;
long curTime = System.currentTimeMillis() & BITMASK;
nextSeed = nextSeed | (curTime << shiftBits);
shiftBits += BITLEN;
if ( shiftBits >= LONGLEN) {
sr.setSeed(nextSeed);
nextSeed = 0;
shiftBits = 0;
}
}
}
public static synchronized void nextBytes(byte[] array) {
seedUp();
sr.nextBytes(array);
}
}