【问题标题】:AES Decryption in pythonpython中的AES解密
【发布时间】:2014-06-18 08:14:28
【问题描述】:

我使用 $.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 烧瓶中的后端解密相同的凭据。

python 代码

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

我在加密和解密时使用了相同的模式,但是 print 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 中使用相同的解密技术。

【问题讨论】:

  • encrypted.toString() 是将密文转换为字符串的不好方法。使用 Base64 或 HEX 文本表示,并在 JS 和 python 代码中进行相应的转换。
  • @OlegEstekhin 你能给我推荐任何可行的例子吗?
  • @OlegEstekhin 我已经更新了我的问题。

标签: python encryption cryptography flask pycrypto


【解决方案1】:

您传递给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

【讨论】:

  • 我阅读了该文档,但我不知道如何在 javascript 端和 python 端使用它。你能推荐我这方面的好文章或工作例子吗?
  • 在更大的范围内,您要解决什么问题?听起来通过 https 检索和发布您的所有数据将满足您的保密要求并解决我认为您遇到的一些其他安全问题。 @Jaydipsinh
  • 看,我想加密用户提供的 aws 凭据,并且需要将该加密的凭据传递给烧瓶中的服务器,我必须解密凭据。这就是我想做的事
  • 因此通过 https 传输凭据,这将确保使用 TLS 进行身份验证和加密的连接,这将比任何人自己构建的任何东西都更好地设计和更安全。 @Jaydipsinh
猜你喜欢
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2019-11-04
  • 2019-10-27
  • 1970-01-01
  • 2018-04-04
  • 2020-12-23
  • 2018-08-16
相关资源
最近更新 更多