python - os.urandom(20) 生成的随机数会重复吗?
高洛峰
高洛峰 2017-04-17 17:34:06
0
2
903

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()
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
洪涛

Basically you can think that the probability of conflict is very low, and the length specified here is 20 bits. It cannot be said that there is no conflict at all, but the probability is very low, and basically there will be no conflict.
See documentation

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.

It says The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

The data returned is "unpredictable" enough to be used for crypto-related encryption.

I did a test and generated 1000W records. There are no duplicates. You can increase the data test intensity and try again. From a statistical point of view, the probability of this very low-probability event can be considered to be 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)),重复下上面的测试, 还是有很大的几率冲突的。
Ty80

Of course it will repeat. Since it is a random number, it will repeat randomly.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!