前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Random来生成随机数的危险性 顶

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

作者头像
算法之名
发布2019-08-20 09:58:24
5800
发布2019-08-20 09:58:24
举报
文章被收录于专栏:算法之名算法之名

我们先来看一个实例

代码语言:javascript
复制
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));
        }
    }
}

运行结果

234 344 737 314 431 423 823 503 703 654

234 344 737 314 431 423 823 503 703 654

经过比对,两次随机出来是不是很神奇,而且无论你随机多少次,结果都一样。这里就有一个种子值的问题。

如果不写种子值,其实Random会有一个默认的种子值,这个值就是 System.currentTimeMillis() ,所以我们在代码开发中,你一般不要使用System.currentTimeMillis()来作为token之类的发送给用户,否则将有可能会作为攻击凭证来获取你的随机数,那么你的随机数将无任何意义。

因为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里面的。

所以基本上,除非黑客控制了你的操作系统,否则很难猜测出你的种子的。

代码语言:javascript
复制
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));
        }

    }
}

运行结果

931 443 917 223 566 858 494 706 539 360

931 443 917 223 566 858 494 706 539 360

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档