SecureRandom产生强随机数简介

SecureRandom是强随机数生成器,主要应用的场景为:用于安全目的的数据数,例如生成秘钥或者会话标示(session ID),弱随机数生成器会产生严重的安全问题,而使用SecureRandom这样的强随机数生成器将会极大的降低出问题的风险。

SecureRandom与Random有很强的关系。

1. SecureRandom继承于Random,看一下它的两个构造函数构造函数:

public SecureRandom()
{
    super(0);//调用Random的构造函数
    getDefaultPRNG(false, null);
}
public SecureRandom(byte seed[])
{
    super(0);//调用Random的构造函数
    getDefaultPRNG(true, seed);
}

2. SecureRandom与Random的常见的两个方法如下所示:

获得一个随机的int数:

public int nextInt() {
        return next(32);
    }

next方法如下:

protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) & mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed >>> (48 - bits));
    }

获得随机的字节数组:

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

获得别的随机数的方法见下图:

想更深入的SecureRandom研究文章,请参考别的资料。

原文地址:https://www.cnblogs.com/longshiyVip/p/4707249.html