How can I create a random number that is cryptographically secure in python?(如何在 python 中创建一个加密安全的随机数?)
问题描述
我正在用 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
nrandom 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().
这篇关于如何在 python 中创建一个加密安全的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 python 中创建一个加密安全的随机数?
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
