如何在python中创建加密安全的随机数?

2024-04-18 16:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python做一个项目,我想创建一个密码安全的随机数,我该怎么做?我在网上看到,由常规随机数发生器生成的数字不是加密安全的,函数os.urandom(n)返回给我的是一个字符串,而不是一个数字。


Tags: 项目函数字符串密码os数字urandom常规
3条回答

因为您希望在某个特定范围内生成整数,所以使用random.SystemRandom类要容易得多。创建该类的实例将为您提供一个对象,该对象支持random模块的所有方法,但在封面下使用os.urandom()。示例:

>>> from random import SystemRandom
>>> cryptogen = SystemRandom()
>>> [cryptogen.randrange(3) for i in range(20)] # random ints in range(3)
[2, 2, 2, 2, 1, 2, 1, 2, 1, 0, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0]
>>> [cryptogen.random() for i in range(3)]  # random floats in [0., 1.)
[0.2710009745425236, 0.016722063038868695, 0.8207742461236148]

等等,直接使用urandom(),你必须发明自己的算法,将它产生的随机字节转换成你想要的结果。别那么做;-)SystemRandom替你做。

注意文档的这一部分:

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state and sequences are not reproducible. Accordingly, the seed() and jumpahead() methods have no effect and are ignored. The getstate() and setstate() methods raise NotImplementedError if called.

只需对^{}返回的字节应用^{}函数,就可以得到随机数列表,如下所示

>>> import os
>>> os.urandom(10)
'm\xd4\x94\x00x7\xbe\x04\xa2R'
>>> type(os.urandom(10))
<type 'str'>
>>> map(ord, os.urandom(10))
[65, 120, 218, 135, 66, 134, 141, 140, 178, 25]

引用os.urandom文档

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().

Python 3.6引入了一个新的secrets module,它“提供对操作系统提供的最安全的随机源的访问”。为了生成一些加密的安全号码,可以调用^{}

secrets.randbelow(n)

它将返回一个介于0和n之间的数字。

相关问题 更多 >