使用AES-256加密,如使用PyCrypto的OpenSSL

时间:2017-03-13 12:48:42

标签: python encryption cryptography pycrypto

我正在尝试使用AES-256加密时间戳,使用base64加密Python。使用此命令生成OpenSSL等效输出:

openssl enc -aes256 -pass pass:'1Lw2*kx18#AvNuij*iRL1nY1UA_#k8$+' -nosalt -base64 <<< "1489355323"

我的python代码如下:

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命令相同的输出。知道我做错了吗?

1 个答案:

答案 0 :(得分:3)

OpenSSL enc命令使用的密钥和iv是EVP_BytesToKey函数从密码派生的。您需要重现该函数以使代码以相同的方式运行。

在Python中它可能看起来像:

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正在考虑在未来提供更新的密钥派生功能。

您还需要注意换行。 here字符串(<<<)在字符串末尾添加换行符,您需要将其添加到要加密的字符串中以获得相同的结果:

timestamp = "1489355323\n"