如何在python中创建一个加密安全的随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20936993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a random number that is cryptographically secure in python?
提问by user2835118
I'm making a project in python and I would like to create a random number that is cryptographically secure, How can I do that? I have read online that the numbers generated by the regular randomizer are not cryptographically secure, and that the function os.urandom(n)returns me a string, and not a number.
我正在用 python 制作一个项目,我想创建一个加密安全的随机数,我该怎么做?我在网上读到,常规随机生成器生成的数字在密码上不安全,并且该函数os.urandom(n)返回一个字符串,而不是数字。
采纳答案by thefourtheye
You can get a list of random numbers by just applying ordfunction over the bytes returned by os.urandom, like this
您可以ord通过对 返回的字节应用函数来获取随机数列表os.urandom,如下所示
>>> 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]
Quoting os.urandomdocumentation,
引用os.urandom文档,
Return a string of
nrandom 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 useCryptGenRandom().
返回一串适合加密使用的
n随机字节。此函数从特定于操作系统的随机源返回随机字节。返回的数据对于加密应用程序来说应该是不可预测的,尽管它的确切质量取决于操作系统的实现。在类 UNIX 系统上,这将查询
/dev/urandom,而在 Windows 上它将使用CryptGenRandom().
回答by Tim Peters
Since you want to generate integers in some specific range, it's a lot easier to use the random.SystemRandomclass instead. Creating an instance of that class gives you an object that supports all the methods of the randommodule, but using os.urandom()under the covers. Examples:
由于您希望生成某个特定范围内的整数,因此使用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]
Etc. Using urandom()directly, you have to invent your own algorithms for converting the random bytes it produces to the results you want. Don't do that ;-) SystemRandomdoes it for you.
等等。urandom()直接使用,你必须发明你自己的算法来将它产生的随机字节转换为你想要的结果。不要那样做 ;-) SystemRandom为你做。
Note this part of the docs:
请注意文档的这一部分:
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.
类 random.SystemRandom([种子])
使用 os.urandom() 函数从操作系统提供的源生成随机数的类。并非在所有系统上都可用。不依赖软件状态,序列不可重现。因此,seed() 和 jumpahead() 方法无效并被忽略。如果调用 getstate() 和 setstate() 方法会引发 NotImplementedError 。
回答by jjlin
If you want an n-bit random number, under Python 2.4+, the easiest method I've found is
如果你想要一个n-bit 随机数,在 Python 2.4+ 下,我发现的最简单的方法是
import random
random.SystemRandom().getrandbits(n)
Note that SystemRandomuses os.urandom(), so the result of this method is only as good as your system's urandom()implementation.
请注意,SystemRandom使用os.urandom(),因此此方法的结果仅与系统的urandom()实现一样好。
回答by Cody Piersall
Python 3.6introduces a new secrets module, which "provides access to the most secure source of randomness that your operating system provides." In order to generate some cryptographically secure numbers, you can call secrets.randbelow().
Python 3.6引入了一个新的secrets 模块,它“提供对操作系统提供的最安全的随机源的访问”。为了生成一些加密安全的数字,您可以调用secrets.randbelow().
secrets.randbelow(n)
which will return a number between 0 and n.
这将返回一个介于 0 和n.
回答by TheGamePlayer 40
To generate a cryptographically secure pseudorandom integer, you can use the following code:
要生成加密安全的伪随机整数,您可以使用以下代码:
int(binascii.hexlify(os.urandom(n)),16)
Where nis an integer and, the larger nis, the larger the integer generated is.
其中n是整数,越大n生成的整数越大。
You will have to import osand binasciifirst.
您必须先导入os和binascii。
The result of this code can vary by platform.
此代码的结果可能因平台而异。

