从 SecureRandom 获取确定性值? [英] Get deterministic values from SecureRandom?
问题描述
出于基准测试目的,我希望 SecureRandom 产生确定性输出.这是否可以通过使用种子(或算法规范)来实现?
For benchmarking purposes, I'd like to have a SecureRandom produce deterministic output. Is this possible through the use of a seed (or maybe specification of an algorithm)?
import java.security.SecureRandom;
class TestSecureRandom {
public static void main(String [] args) {
SecureRandom rnd = new SecureRandom();
rnd.setSeed(1);
System.out.println(rnd.nextInt());
}
}
对我来说,即使指定了种子,上述程序也会产生不同的值.
For me, the above program produces different values even though the seed is specified.
推荐答案
最简单的方法可能是让你的大部分代码只依赖于 Random
,并注入一个实例(例如通过将其传递给构造函数).这样,出于测试目的,您可以传入一个带有固定种子的简单 Random
- 但对于需要安全性的 real 运行,您可以传入一个 实例>SecureRandom
.
The simplest way of doing this is probably to make most of your code only depend on Random
, with an instance being injected (e.g. by passing it into a constructor). That way, for testing purposes you can pass in a simple Random
with a fixed seed - but for real runs where security is required, you can pass in an instance of SecureRandom
.
这篇关于从 SecureRandom 获取确定性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!