java.security.SecureRandom使用介绍
- 2016-06-27
- admin
- 原创 5732
一、java.security.SecureRandom使用介绍
1、SecureRandom提供cryptographically strong random number generator;
2、SecureRandom实现伪随机数、真随机数、两者混合;
3、SecureRandom继承Random;
4、默认随机数算法SHA1PRNG;
5、SecureRandom()第一次获取随机数时使用随机源初始化种子,SecureRandom(byte[] seed)构造对象时初始化种子;
6、getSeed和generateSeed使用随机源,nextBytes使用随机算法;
7、Random、SecureRandom、ThreadLocalRandom都是线程安全;
8、ThreadLocalRandom性能最高,但不是加密安全,ThreadLocalRandom.current()获取当前线程随机数实例;
9、TLR设置变量java.util.secureRandomSeed=true,则调用SecureRandom.getSeed,则使用加密安全种子;
二、Java配置随机源
1、设置启动变量:-Djava.security.egd=file:/dev/random,-Djava.security.egd=file:/dev/urandom
2、修改配置文件jre\lib\security\java.security
securerandom.source=file:/dev/random,非默认
securerandom.source=file:/dev/urandom,默认值
三、Java总是取到阻塞随机源BUG
代码分析1:
SeedGenerator instance;
if ((str.equals("file:/dev/random")) || (str.equals("file:/dev/urandom")))
instance = new NativeSeedGenerator();
else if (str.length() != 0)
instance = new URLSeedGenerator(str);
代码分析2:
class NativeSeedGenerator extends SeedGenerator.URLSeedGenerator
代码分析3:
URLSeedGenerator() throws IOException {
this("file:/dev/random");
}
如何使用非阻塞随机源:
-Djava.security.egd=file:/dev/./urandom
四、测试代码和结果输出
public static void testSecureRandom1() {
byte seed[] = {1, 2, 3, 4};
SecureRandom random = new SecureRandom(seed);
byte bytes[] = new byte[8];
random.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
}
public static void testSecureRandom2(int idx) {
System.out.println(String.format(
"nextBytes count is %d.", idx));
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[8];
random.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
}
public static void testSecureRandom3(int idx) {
System.out.println(String.format(
"generateSeed count is %d.", idx));
SecureRandom random = new SecureRandom();
byte bytes[] = random.generateSeed(8);
System.out.println(Arrays.toString(bytes));
}
public static void main(String[] args) {
int idx;
testSecureRandom1();
testSecureRandom1();
for (idx = 1; idx <= 3; ++idx)
testSecureRandom2(idx);
for (idx = 1; idx <= 3; ++idx)
testSecureRandom3(idx);
}
输出结果:
[-14, 77, 123, 121, 116, 50, -89, -86]
[-14, 77, 123, 121, 116, 50, -89, -86]
nextBytes count is 1.
[-1, 110, -82, 91, 57, -52, 8, 99]
nextBytes count is 2.
[-80, 65, -68, -27, 126, -88, -76, 54]
nextBytes count is 3.
[76, 123, 55, -10, -22, -18, -43, -46]
generateSeed count is 1.
[39, -45, -97, 108, 58, -6, 115, -29]
generateSeed count is 2.
[76, -34, 121, -14, 60, 55, -35, 50]
generateSeed count is 3.
[-13, 21, 60, -31, -89, -16, 84, -100]