使用Random来生成随机数的危险性

咱们先来看一个实例java

public class SecureTest {
    public static void main(String[] args) {
        Random random1 = new Random(23468);
        for (int i = 0;i < 10;i++) {
            System.out.println(random1.nextInt(1000));
        }
        System.out.println("");
        Random random2 = new Random(23468);
        for (int i = 0;i < 10;i++) {
            System.out.println(random2.nextInt(1000));
        }
    }
}

运行结果linux

234
344
737
314
431
423
823
503
703
654app

234
344
737
314
431
423
823
503
703
654dom

通过比对,两次随机出来是否是很神奇,并且不管你随机多少次,结果都同样。这里就有一个种子值的问题。ide

若是不写种子值,其实Random会有一个默认的种子值,这个值就是 System.currentTimeMillis() ,因此咱们在代码开发中,你通常不要使用System.currentTimeMillis()来做为token之类的发送给用户,不然将有可能会做为攻击凭证来获取你的随机数,那么你的随机数将无任何意义。spa

由于Random的种子可预测,咱们能够使用SecureRandom来代替Random,SecureRandom是继承于Random的一个类。虽然相同的种子产生的随机数也相同,但SecureRandom的默认种子将再也不是System.currentTimeMillis(),而是操做系统里面的一些随机事件。操作系统

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.
SecureRandom takes Random Data from your os (they can be interval between keystrokes etc - most os collect these data store them in files - /dev/random and /dev/urandom in case of linux/solaris) and uses that as the seed.
操做系统收集了一些随机事件,好比鼠标点击,键盘点击等等,SecureRandom 使用这些随机事件做为种子
这些事件是存放在/dev/urandom里面的。
因此基本上,除非黑客控制了你的操做系统,不然很难猜想出你的种子的。
public class SecureTest {
    public static void main(String[] args) {
        SecureRandom random1 = new SecureRandom();
        byte[] seeds = SecureRandom.getSeed(64);
        random1.setSeed(seeds);
        for (int i = 0;i < 10;i++) {
            System.out.println(random1.nextInt(1000));
        }
        System.out.println("");
        SecureRandom random2 = new SecureRandom();
        random2.setSeed(seeds);
        for (int i = 0;i < 10;i++) {
            System.out.println(random2.nextInt(1000));
        }

    }
}

运行结果blog

931
443
917
223
566
858
494
706
539
360继承

931
443
917
223
566
858
494
706
539
360token

若是不手工设置种子值,就是取/dev/urandom里面的值做为种子值。

相关文章
相关标签/搜索