java.security.egd

SecureRandom在java各种组件中使用广泛,可以可靠的产生随机数。但在大量产生随机数的场景下,性能会较低。这时可以使用"-Djava.security.egd=file:/dev/./urandom"加快随机数产生过程。

以产生uuid的时候使用nextBytes产生随机数为入口,xSecureRandom的代码逻辑。

   public static UUID randomUUID() {
        SecureRandom ng =Holder.numberGenerator;
 
        byte[] randomBytes = newbyte[16];
        ng.nextBytes(randomBytes);
        randomBytes[6] &= 0x0f;  /* clear version       */
        randomBytes[6]  |=0x40;  /* set to version 4     */
        randomBytes[8] &= 0x3f;  /* clear variant       */
        randomBytes[8]  |=0x80;  /* set to IETF variant  */
        return newUUID(randomBytes);
    }

使用了SecureRandom.next*的方法。

在使用SecureRandom产生下一个随机数的时候调用nextLong或者nextBytes,最终会调用SecureRandom的nextBytes。

    public long nextLong() { 
        // it's okay that the bottom wordremains signed. 
        return ((long)(next(32)) << 32)+ next(32); 
    } 
 
    final protected int next(int numBits) { 
        int numBytes = (numBits+7)/8; 
        byte b[] = new byte[numBytes]; 
        int next = 0; 
 
        nextBytes(b);
        for (int i = 0; i < numBytes; i++) 
            next = (next << 8)+ (b[i] & 0xFF); 
        return next >>> (numBytes*8 -numBits); 
    }

而nextBytes是一个同步的方法,在多线程使用时,可能会产生性能瓶颈。

synchronized public void nextBytes(byte[] bytes) { 
       secureRandomSpi.engineNextBytes(bytes); 
    }

secureRandomSpi被初始化为sun.security.provider.SecureRandom

secureRandomSpi是SecureRandom.NativePRNG的一个实例。

使用jvm参数-Djava.security.debug=all ,可以打印securityprovider列表,从中可以看出,SecureRandom.NativePRNG由sun.security.provider.NativePRNG提供服务。

Provider: Set SUN provider property[SecureRandom.NativePRNG/sun.security.provider.NativePRNG]

 

分析openjdk的源码,NativePRNG.engineNextBytes调用了NativePRNG.RandomIO.ensureBufferValid,而ensureBufferValid直接从urandom读取数据:

private void ensureBufferValid() throws IOException {
            ...
            readFully(urandomIn, urandomBuffer);
            ...
        }

通过测试可以发现,hotspot需要使用配置项"-Djava.security.egd=file:/dev/./urandom"才能从urandom读取数据,这里openjdk做了优化,直接从urandom读取数据。

/dev/random在产生大量随机数的时候比/dev/urandom慢,所以,建议在大量使用随机数的时候,将随机数发生器指定为/dev/./urandom。

 

转自:https://blog.51cto.com/leo01/1795447

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值