用python解密crypto-js中AES加密的密碼

CryptoJS加密:javascript

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實現以下:java

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) < output:
        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
相關文章
相關標籤/搜索