简体   繁体   English

我如何为 aes 加密生成随机密钥

[英]How can i generate random key for aes encryption

I'm new on python.我是python的新手。 I'm working on this code about file encryption with AES我正在处理有关使用 AES 进行文件加密的代码

https://stackoverflow.com/a/20868265/2955896 https://stackoverflow.com/a/20868265/2955896

it uses this key for encryption它使用此密钥进行加密

key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'

How can I generate the key randomly in order to make decryption not possible?如何随机生成密钥以使无法解密?

The most practical way is to read random data from whichever random device your operating system supplies.最实用的方法是从操作系统提供的任何随机设备读取随机数据。 This is conveniently accessed by using os.random() ;这可以通过使用os.random()方便地访问;

In [1]: import os

In [2]: os.urandom(128)[:10]
Out[2]: b'\xee&\x06s?\x8d\xfcI=\x07'

(Only showing the first 10 bytes for convenience.) (为方便起见,仅显示前 10 个字节。)

This will return different data every time you call it;每次调用它都会返回不同的数据;

In [3]: os.urandom(128)[:10]
Out[3]: b')\x12TQ\xf5\xa3G\xe2\xb00'

In [4]: os.urandom(128)[:10]
Out[4]: b'\xce\xba\xd2Gr\x8c6\xba\xb7\x91'

In [5]: os.urandom(128)[:10]
Out[5]: b'~\x00\xca\x0c=\xd3\xff\xef\xc8\x14'

In [6]: os.urandom(128)[:10]
Out[6]: b'\xb0~vb"\xd6(F\xb7v'

Edit:编辑:

From Python 3.6 onwards you should use the secrets module for cryptograhically strong random numbers.从 Python 3.6 开始,您应该将secrets模块用于加密强随机数。 For example:例如:

In [1]: import secrets

In [2]: secrets.token_urlsafe(32)
Out[2]: 'SgkZmSckZcSB3a4uK-SFPN6vevgx231sHs-aE5GlP-g'

As of 2015, 32 is the default number of bytes requested;截至 2015 年,32 是请求的默认字节数;

In [3]: secrets.token_urlsafe()
Out[3]: 'qbmwK_2-_f6UQOTLJcweYcwZQze8lo3dtIuEKWhpb_w'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM