SecureRandom的坑

之前写随机数的时候一直用SecureRandom.getInstanceStrong()方法生成SecureRandom实例,进而调用其各种next方法。突然有一次,发现next方法卡住了, 每一次调用都需要四五分钟。google之,发现网上也有很多其他开发人员在反馈这个问题,有的说在启动的时候提案加    。但是有时候项目不是自己部署的,不是你想用什么命令就用什么命令,想替换什么文件就替换什么文件,比如某安某寿。研究SecureRandom.getInstanceStrong()方法的源码,发现最终调用的是SecureRandom.getInstance()方法,getInstance()方法的入参是Security.getProperty("securerandom.strongAlgorithms")的返回值。经测试,Security.getProperty("securerandom.strongAlgorithms")的返回值在不同平台是不一样。在windows jdk中,返回值是Windows-PRNG:SunMSCAPI,SHA1PRNG:SUN,进SecureRandom.getInstanceStrong()方法,发现最终调用的是SecureRandom.getInstance("Windows-PRNG", "SunMSCAPI"),即算法algorithm是Windows-PRNG,provider是SunMSCAPI。在mac jdk中,返回值是。在linux jdk中,返回值是。

研究Security的getProperty(String key)静态方法:

读取的是JAVA_HOME/jre/lib/security目录中的java.security属性文件中的内容。可以很容易的在各平台看到securerandom.strongAlgorithms的值。

如果不用SecureRandom.getInstanceStrong()方法的话,可以用什么呢?可以用new SecureRandom(),也可以用getInstance()方法的一堆重载来生成SecureRandom实例。

new SecureRandom(),最终调用的是SecureRandom.getInstance("SHA1PRNG")。

在java.security文件中,有这样一段描述:

#
# Sun Provider SecureRandom seed source.
#
# Select the primary source of seed data for the "SHA1PRNG" and
# "NativePRNG" SecureRandom implementations in the "Sun" provider.
# (Other SecureRandom implementations might also use this property.)
#
# On Unix-like systems (for example, Solaris/Linux/MacOS), the
# "NativePRNG" and "SHA1PRNG" implementations obtains seed data from
# special device files such as file:/dev/random.
#
# On Windows systems, specifying the URLs "file:/dev/random" or
# "file:/dev/urandom" will enable the native Microsoft CryptoAPI seeding
# mechanism for SHA1PRNG.
#
# By default, an attempt is made to use the entropy gathering device
# specified by the "securerandom.source" Security property. If an
# exception occurs while accessing the specified URL:
#
# SHA1PRNG:
# the traditional system/thread activity algorithm will be used.
#
# NativePRNG:
# a default value of /dev/random will be used. If neither
# are available, the implementation will be disabled.
# "file" is the only currently supported protocol type.
#
# The entropy gathering device can also be specified with the System
# property "java.security.egd". For example:
#
# % java -Djava.security.egd=file:/dev/random MainClass
#
# Specifying this System property will override the
# "securerandom.source" Security property.
#
# In addition, if "file:/dev/random" or "file:/dev/urandom" is
# specified, the "NativePRNG" implementation will be more preferred than
# SHA1PRNG in the Sun provider.
#
securerandom.source=file:/dev/random

在commons-lang3.jar包中,提供了两个随机工具类,RandomUtils和RandomStringUtils,可以使用。RandomUtils用于生成一个随机数字,而RandomStringUtils主要是生成一个随机字符串。这俩工具类底层利用的都是Random类,而没有用SecureRandom。

猜你喜欢

转载自www.cnblogs.com/koushr/p/11783607.html