生成可预测的安全随机数

lya*_*ffe 2 java random secure-random

如何实例化可预测且安全的随机数生成器,该生成器将在 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)

lsc*_*lin 5

您想要做的是使用SecureRandom.getInstance使用旧算法获取安全随机实例。

下面的示例代码。您应该考虑天气与否,这是否是您真正想要的行为。

    public void example() throws NoSuchAlgorithmException {
    {
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(12345678L);
        System.out.println(secureRandom.nextLong());

    }
    {
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(12345678L);
        System.out.println(secureRandom.nextLong());

    }

}
Run Code Online (Sandbox Code Playgroud)

这吐出来:

3325995872096263519
3325995872096263519
Run Code Online (Sandbox Code Playgroud)

就像你正在寻找的那样。