我们有业务要求生成随机临时密码。根据用例,预计此类呼叫的数量非常低(约400个呼叫/天)。我们决定使用java.security.SecureRandom
来实现加密强大的随机化,根据互联网上的各种建议,并在阅读了SO上的许多类似帖子之后。
现在,我们编写了一个简单的随机数发生器(内部使用SecureRandom
),它应该在Web应用程序中用作singleton
。但是,我们也会定期根据SO的建议重新安排它。为此,下面是一些实现相同的示例代码。有人可以检查一下,如果这是正确且合理有效的方法,请告诉我们吗?另外,有没有办法避免代码中的synchronization
,同时仍然保持线程安全?:
import java.security.*;
public final class Randomizer {
private static final Randomizer INSTANCE = new Randomizer();
private static final String DEFAULT_CSPRNG_ALGO = "SHA1PRNG";
private volatile SecureRandom sr;
private volatile long lastSeedTime;
public static final Randomizer getInstance() throws Exception {
return INSTANCE;
}
public int nextInt(int len) throws RuntimeException {
reseedRandomAsNeeded();
return sr.nextInt(len);
}
private Randomizer() throws RuntimeException {
try {
System.out.printf("%s Constructing Randomizer...%n", Thread.currentThread());
recreateSecureRandomInstance();
lastSeedTime = System.nanoTime();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* TODO Is there a way to avoid the synchronization overhead here? We really
* only need to synchronize when the reseed happens.
*
* @throws RuntimeException
*/
private synchronized void reseedRandomAsNeeded() throws RuntimeException {
if (isItTimeToReseed()) {
// TODO Need to do a reseed. Just get a new SecureRandom for now.
try {
recreateSecureRandomInstance();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
private boolean isItTimeToReseed() {
boolean reseed = false;
long currentTime = System.nanoTime();
long difference = ((currentTime - this.lastSeedTime) / (1000 * 1000 * 1000)/* *60 * 60 * 24*/);
// System.out.printf("%s Current time: %d, Last Reseed Time: %d, difference: %d%n",
// Thread.currentThread(), currentTime, lastSeedTime, difference);
// TODO For testing, test for just a 3 seconds difference.
if (difference > 3) {
reseed = true;
this.lastSeedTime = currentTime;
}
return reseed;
}
private void recreateSecureRandomInstance() throws NoSuchAlgorithmException {
sr = SecureRandom.getInstance(DEFAULT_CSPRNG_ALGO);
System.out.printf("%s Created a new SecureRandom instance: %s%n", Thread.currentThread(), sr);
}
}
答案 0 :(得分:1)
您可以根据调用次数重新设置,而不是基于时间。
在班级中维护一个计数器,并在每次调用随机生成器时增加它。当计数器达到某个阈值时,重新设置它并将计数初始化为0。 您可以重新调整每100万次调用的次数。
这是我唯一可以建议的。