如何创建一个在Python中加密安全的随机数? [英] How can I create a random number that is cryptographically secure in python?

查看:213
本文介绍了如何创建一个在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)
'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 文件,


返回 n 随机字节适用于加密使用的字符串。

此函数返回来自特定于OS的随机源的随机字节。返回的数据对于加密应用程序应该是不可预测的,尽管其确切的质量取决于OS实现。在类似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中加密安全的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆