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

2022-01-10 00:00:00 python random cryptography

问题描述

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

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.


解决方案

只要应用 ord 函数对 os.urandom,像这样

You can get a list of random numbers by just applying ord function over the bytes returned by os.urandom, like this

>>> import os
>>> os.urandom(10)
'mxd4x94x00x7xbex04xa2R'
>>> type(os.urandom(10))
<type 'str'>
>>> map(ord, os.urandom(10))
[65, 120, 218, 135, 66, 134, 141, 140, 178, 25]

引用 os.urandom 文档,

返回一串 n 随机字节适合加密使用.

Return a string of n random bytes suitable for cryptographic use.

此函数从特定于操作系统的随机源返回随机字节.返回的数据对于加密应用程序来说应该是不可预测的,尽管它的确切质量取决于操作系统的实现.在类 UNIX 系统上,这将查询 /dev/urandom,而在 Windows 上,它将使用 CryptGenRandom().

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

相关文章