CryptoJS加密:
var data = "测试字符串";
var passphrase = "passphrase";
var encrypted = CryptoJS.AES.encrypt(data, passphrase).toString();
console.log(encrypted);
加密后输出类似如下字符串:
U2FsdGVkX187CV++0s/Eoo6Y4O1mJqcbofVFvTfBU5g=
CryptoJS的AES算法默认是CBC模式和PKCS#7填充,密钥大小为256位,IV是128位块大小。这意味着我们必须从EVP_BytesToKey请求32 + 16 = 48个字节。
python实现如下:
from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5
def pad(data):
length = 16 - (len(data) % 16)
return data + (chr(length)*length).encode()
def unpad(data):
return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
def bytes_to_key(data, salt, output=48):
# extended from https://gist.github.com/gsakkis/4546068
assert len(salt) == 8, len(salt)
data += salt
key = md5(data).digest()
final_key = key
while len(final_key)
key = md5(key + data).digest()
final_key += key
return final_key[:output]
def encrypt(message, passphrase):
salt = Random.new().read(8)
key_iv = bytes_to_key(passphrase, salt, 32+16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))
def decrypt(encrypted, passphrase):
encrypted = base64.b64decode(encrypted)
assert encrypted[0:8] == b"Salted__"
salt = encrypted[8:16]
key_iv = bytes_to_key(passphrase, salt, 32+16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return unpad(aes.decrypt(encrypted[16:]))
测试:
passphrase = "passphrase"
test = "U2FsdGVkX187CV++0s/Eoo6Y4O1mJqcbofVFvTfBU5g="
result = decrypt(test, passphrase)
print(result)
原文:https://stackoverflow.com/questions/36762098/how-to-decrypt-password-from-javascript-cryptojs-aes-encryptpassword-passphras