使用PyCrypto使用AES-256(如OpenSSL)进行加密 [英] Encrypt using AES-256 like OpenSSL with PyCrypto
问题描述
我正在尝试使用AES-256和带有base64的Python加密时间戳。使用以下命令生成与输出等效的OpenSSL:
I'm trying to encrypt a timestamp using AES-256 and Python with base64. The OpenSSL equivalent of the output is generated with this command:
openssl enc -aes256 -pass pass:'1Lw2*kx18#AvNuij*iRL1nY1UA_#k8$+' -nosalt -base64 <<< "1489355323"
我的python代码如下:
My python code looks like so:
import time
from base64 import b64encode
from Crypto.Cipher import AES
key = '1Lw2*kx18#AvNuij*iRL1nY1UA_#k8$+'
timestamp = "1489355323"
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
iv = "\x00" * 16
aes = AES.new(key, AES.MODE_CBC, iv)
ciphertext = aes.encrypt( pad( timestamp ) )
print b64encode(ciphertext)
当前输出不同,我需要获得与OpenSSL命令相同的输出。知道我在做什么错吗?
Currently the output is different, and I need to get the same output as the OpenSSL command. Any idea what I'm doing wrong?
推荐答案
OpenSSL enc的密钥和iv
命令的使用是通过 EVP_BytesToKey
函数。您将需要重现该函数以使您的代码具有相同的行为。
The key and iv that the OpenSSL enc
command use are derived from the password by the EVP_BytesToKey
function. You will need to reproduce that function to get your code to behave the same way.
在Python中,它看起来可能像是:
In Python it might look like:
from hashlib import md5
# ...
last = ''
bytes = ''
# 32 byte key (256 bits) + 16 byte IV = 48 bytes needed
while len(bytes) < 48:
last = md5(last + password).digest()
bytes += last
key = bytes[0:32]
iv = bytes[32:48]
# ...
aes = AES.new(key, AES.MODE_CBC, iv)
ciphertext = aes.encrypt( pad( timestamp ) )
实际上不再建议使用此方案,但是 enc
命令仍然使用它。我相信OpenSSL希望在将来提供更新的密钥派生功能。
This scheme isn’t really recommended anymore, but the enc
command still uses it. I believe OpenSSL is looking at providing a more up to date key derivation function in the future.
您还需要注意换行符。这里的字符串(<<<
)在字符串末尾添加换行符,您需要将其添加到要加密的字符串中以获得相同的结果:
You also need to take care with newlines. The here string (<<<
) adds a newline to the end of the string, you would need to add that to the string you are encrypting to get identical results:
timestamp = "1489355323\n"
这篇关于使用PyCrypto使用AES-256(如OpenSSL)进行加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!