这个答案假定你知道你在做什么.在其他情况下,应尽量减少使用/ dev / random.
/ dev / random就像普通文件一样,因此任何可以读取任何文件的程序都可以从/ dev / random读取.你可能知道,cat / dev / random直接从中输出随机数据,如果它足够快,你可能实际上想要使用它.所以,如果一切都失败了,你总是能够直接读取这个文件…
A NativePRNG-like class that uses /dev/random for both seed and random material. Note that it does not respect the egd properties, since we have no way of knowing what those qualities are. This is very similar to the outer NativePRNG class, minimizing any breakage to the serialization of the existing implementation.
Since:
1.8
问题可能是从1.8开始,如果您不能使用Java 8,则可以将其运行到较早的平台.源代码完全可用.
所以现在让我们把它放在代码中:
我们必须选择具体的实现来使用.要找到确切的名称,我们输出所有可用的服务与以下行:
for (Provider p: Security.getProviders()) p.getServices().forEach(System.out::println);
然后我们在那里搜索Native,我们找到以下条目:
SUN: SecureRandom.NativePRNGBlocking -> sun.security.provider.NativePRNG$Blocking
这意味着我们可以实例化如下所示的SecureRandom对象来做你想要的:
SecureRandom sr = SecureRandom.getInstance("NativePRNGBlocking", "SUN");
一个简单的测试
byte[] b = new byte[10000];
sr.nextBytes(b);
System.out.println(Arrays.toString(b));
需要年龄,我不得不降低读取字节的数量.如果它适用于您,恭喜您,您正在/ dev / random阅读
注意,这个类是在sun.security.provider包中,不能保证在任何地方都可用.例如,它可能无法在Android上运行.如果这样很好,那么这个解决方案将会工作,否则你应该直接把它看作一个文件.
不要在Android上从/ dev / random中读取.请.