"随机数不随机"???

前言

又摸了一天鱼, 看系统设计中关于安全模块时有提到SecureRandom生成安全随机数的要求, 第一次听说这词儿, 那就研究研究, 写一篇hao123.

正文

Random和SecureRandom区别

之前有一篇记录了java获取某个范围内的一个随机数的方法, 用到的是Random

猿友们大都提到"random是通过系统当前时间的毫秒值作为随机数的种子, 生成随机数, 这样的随机数是可预测的", 说法不准确, 确切地说是系统当前时间的纳秒值参与生成了随机数的种子, 当并发情况下, 多个线程产生的种子有可能是一样的, 也就是生成的是伪随机数.

public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    private static long seedUniquifier() {
        long current;
        long next;
        do {
            current = seedUniquifier.get();
            next = current * 1181783497276652981L;
        } while(!seedUniquifier.compareAndSet(current, next));

        return next;
    }

    public Random(long seed) {
        this.haveNextNextGaussian = false;
        if (this.getClass() == Random.class) {
            this.seed = new AtomicLong(initialScramble(seed));
        } else {
            this.seed = new AtomicLong();
            this.setSeed(seed);
        }

    }

 

也就是说Random的随机数是可预测的。可预测有什么危险呢,可以看两个案例:

SecureRandom类收集了一些随机事件,比如鼠标点击,键盘点击等等,SecureRandom 使用这些随机事件作为种子。这意味着,种子是不可预测的,而不像Random默认使用系统当前时间的毫秒数作为种子,有规律可寻。

SecureRandom怎么用

创建random实例时, 用SecureRandom, 创建实例时还有其他方式, 通常下面这个就够用了. 其他方式见感谢栏中的链接.

SecureRandom random = new SecureRandom();

如果涉及安全不过关, 需要加种子什么的, 那就再整改

 

感谢

https://www.cnblogs.com/deng-cc/p/8064481.html

SecureRandom的正确使用

SecureRandom的漏洞与正确打开方式

 

posted @ 2020-08-24 19:14  习惯沉淀  阅读(484)  评论(0编辑  收藏  举报