开发者社区> 问答> 正文

os.urandom(20) 生成的随机数会重复吗?

os.urandom(20) 生成的随机数会重复吗?

这里的 urandom 应该是调用的系统的随机方法吧

在 Django REST Framework 中 Token 的生成方法

def save(self, args, *kwargs):

if not self.key:
    self.key = self.generate_key()
return super(Token, self).save(*args, **kwargs)

def generate_key(self):

return binascii.hexlify(os.urandom(20)).decode()

展开
收起
a123456678 2016-06-27 14:38:08 4675 0
1 条回答
写回答
取消 提交回答
  • 基本上你可以认为,冲突的概率很低了,而且这里指定的是20位的长度,不能说完全没冲突,但是这个概率非常低,基本上认为不会冲突了。
    见文档

    os.urandom(n)
    Return a string of n random bytes suitable for cryptographic use.
    This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.
    On a UNIX-like system this will query /dev/urandom, and on Windows it will use
    CryptGenRandom(). If a randomness source is not found, NotImplementedError will be raised.
    For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom.
    里面说 The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

    返回的数据是足够的“不可预测的”,以便用于crypto相关的加密。

    做了一个测试,产生了1000W条记录,没有重复的,你可以增大数据测试强度再试试。这种非常小概率的事件,从统计的角度来讲,可以认为概率为0.

    全选复制放进笔记

    -- coding: utf-8 --

    import binhex
    import binascii

    import os
    test = {}
    for i in range(1000*10000):

    c = binascii.hexlify(os.urandom(20)).decode()
    if c not in test:
        test[c] = 1
    else:
        print "duplicate " + str(i)
        break
    

    print "finished"

    你可以试试把生成的数据长度20改成小点的数,比如4(os.urandom(4)),重复下上面的测试, 还是有很大的几率冲突的。

    2019-07-17 19:47:35
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载