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

查看:30
本文介绍了如何在python中创建一个加密安全的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

只需应用 ord 函数处理 os.urandom,像这样

<预><代码>>>>导入操作系统>>>os.urandom(10)'mxd4x94x00x7xbex04xa2R'>>>类型(os.urandom(10))<输入'str'>>>>地图(ord,os.urandom(10))[65, 120, 218, 135, 66, 134, 141, 140, 178, 25]

引用 os.urandom 文档,

<块引用>

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

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

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.

解决方案

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]

Quoting os.urandom documentation,

Return a string of n random 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 use CryptGenRandom().

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

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