Encrypt using AES-256 like OpenSSL with PyCrypto

依然范特西╮ 提交于 2019-12-12 22:52:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!