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

How can I create a random number that is cryptographically secure in python?(如何在 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 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().

这篇关于如何在 python 中创建一个加密安全的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)