Python中的AES解密

时间:2014-06-18 08:14:28

标签: python encryption cryptography flask pycrypto

我正在使用$ .ajax方法从前端发送凭证,而我曾使用crypto.js加密凭据。

javascript代码

var encrypted = CryptoJS.AES.encrypt("Message", "This is a key123", { mode: CryptoJS.mode.CFB});

$.ajax({
        type: "POST",
        url: $SCRIPT_ROOT + "/test",
        contentType: "application/json",
        data:JSON.stringify({key:encrypted.toString()}),
        dataType: "json",
        success: function (response) {
            alert(response);
        }
    });

我希望在后端使用python flask解密相同的凭据。

python代码

data = request.json
key = data["key"]
obj2 = AES.new('This is a key123', AES.MODE_CFB)
s = obj2.decrypt(key)
print s

我在加密和解密时使用了相同的模式,但是打印s将打印在字符串下面。

 �Qg%��qNˮ�Ŵ�M��ĦP�
                  "~�JB���w���#]�v?W

任何人都可以建议我在前端和前后加密解密的更好方法吗?后端?

我在python中尝试过相同的加密解密,

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CFB)
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\x1f\x99%8\xa8\x197%\x89U\xb6\xa5\xb6C\xe0\x88'
>>> obj2 = AES.new('This is a key123', AES.MODE_CFB)
>>> obj2.decrypt(ciphertext)
'The answer is no'

它工作正常,但我想使用javascript在前端加密数据,我想在python中使用相同的解密技术。

1 个答案:

答案 0 :(得分:0)

传递给CryptoJS.AES.encrypt的字符串不会像Python代码那样直接用作密钥(在utf8编码之后),而是用作密码以某种方式派生密钥。见:https://code.google.com/p/crypto-js/#The_Cipher_Input

此外,输出也被编码为可打印字符串,并不表示Python代码所需的原始字节字符串。请参阅:https://code.google.com/p/crypto-js/#The_Cipher_Output