Java是否SecureRandom.nextLong()返回所有可能的值,因为它继承了Random仅使用48位的值?如果没有,我是否仍然可以通过修改Random类以及如何进行Java来实现它?我只想使用所有随机长数字生成器,如果可能的话,可以返回所有可能的长值.
我尝试过,SecureRandom.random_number(9**6)但有时返回5,有时返回6。我希望它的长度始终为6。我也更喜欢它的格式,SecureRandom.random_number(9**6)而无需使用类似的语法,6.times.map以便在控制器测试中更容易进行打桩。
我手头有一个难题。我创建了一个 AES 服务来加密/解密敏感信息。AES 密钥是使用 java 的SecureRandom. 我有一个受保护的文件,用于存储种子,并且在调用服务时,种子将填充到安全随机类中。
为了确保它有效,我有以下逻辑:
private boolean secureRandom(final String seed) {
SecureRandom sr1 = new SecureRandom(seed.getBytes(UTF8_CHARSET));
SecureRandom sr2 = new SecureRandom(seed.getBytes(UTF8_CHARSET));
//Two secure random with the same seed should generate the same results
boolean secureRandomWorks = sr1.nextLong() == sr2.nextLong();
if (!secureRandomWorks) {
System.err.println("Secure random not supported. Defaulting to old key");
}
return secureRandomWorks;
}
Run Code Online (Sandbox Code Playgroud)
这里的想法是我应该能够使用相同的种子创建两个安全的随机对象,并且它们在调用时都应该返回相同的值nextLong()
当我在 Windows 计算机上部署应用程序时,这工作正常,但当我将其部署在 RHEL 7 计算机上时,我收到错误。
我的印象是,只要种子相同,两个实例总是会产生相同的输出。在 Windows 上似乎是这种情况,但当我在 RHEL 7 上测试时,情况似乎并非如此。
我创建了这个简单的测试来进行验证:
SecureRandom sr1 = new SecureRandom("encryptionKey".getBytes("UTF-8"));
SecureRandom …Run Code Online (Sandbox Code Playgroud) 如何实例化可预测且安全的随机数生成器,该生成器将在 Java 版本和操作系统之间生成一致的随机数?
以下代码曾经适用于 Java 8,但不再适用于 Java 10:
import java.security.SecureRandom;
public class PredictableRandom {
public static void main(String[] args) {
PredictableRandom predictableRandom = new PredictableRandom();
predictableRandom.execute();
}
private void execute() {
SecureRandom secureRandom = new SecureRandom();
System.out.println(secureRandom.getAlgorithm());
System.out.println(secureRandom.getProvider());
long seed = 12345678L;
secureRandom.setSeed(seed);
System.out.println(secureRandom.nextLong());
SecureRandom secureRandom2 = new SecureRandom();
secureRandom2.setSeed(seed);
System.out.println(secureRandom2.nextLong());
}
}
Run Code Online (Sandbox Code Playgroud)
在 Java 8 中 - 好的,不同的随机对象生成相同的随机数:
SHA1PRNG
SUN version 1.8
3325995872096263519
3325995872096263519
Run Code Online (Sandbox Code Playgroud)
在 Java 10 中 - 不好,不同的随机对象生成不同的随机数:
DRBG
SUN version 10
-3526685326322256981
-2373261409119309182
Run Code Online (Sandbox Code Playgroud) 使用SecureRandom是否可以保证2个连续调用不会返回相同的数字?
如果这是客户端 API 端的严格要求,那么代码中的以下循环是否多余?
Random random = SecureRandom.getInstance("SHA1PRNG");
long value1 = (long)(r.nextDouble() * LIMIT) + 1;
long value2 = (long)(r.nextDouble() * LIMIT);
while(value1 == value2) {
value2 = (long)(r.nextDouble() * LIMIT);
}
Run Code Online (Sandbox Code Playgroud) java ×4
random ×3
generator ×1
integer ×1
long-integer ×1
rhel ×1
rhel7 ×1
rspec-rails ×1
ruby ×1
sha1 ×1