问题
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"
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)
Currently the output is different, and I need to get the same output as the OpenSSL command. Any idea what I'm doing wrong?
回答1:
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.
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 ) )
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"
来源:https://stackoverflow.com/questions/42764041/encrypt-using-aes-256-like-openssl-with-pycrypto