【问题标题】:Encrypting and Decrypting with python and nodejs使用 python 和 nodejs 加密和解密
【发布时间】:2017-08-28 03:49:19
【问题描述】:

我正在尝试在 Python 和 Node.js 应用程序之间传递数据。为此,我正在使用 AES 加密。问题是 Node.js 生成的加密数据比使用 Python 生成的数据长两倍。

下面是代码sn-ps。

Python 3.6

import binascii
from Crypto.Cipher import AES

key = 'key-xxxxxxxxxxxxxxxxxxZZ'
iv = '1234567812345678'
data = 'some_secret_data'

def _encrypt(data):
    aes = AES.new(key, AES.MODE_CBC, iv[:16])
    encrypted = aes.encrypt(data)
    # encrypted = b'\xd54\xbb\x96\xd3\xbet@\x10\x01 [\reg\xaa'

    encrypted_base64 = binascii.b2a_base64(encrypted)
    # encrypted_base64 = b'1TS7ltO+dEAQASBbDWVnqg==\n'

    encrypted_hex = binascii.hexlify(encrypted)
    # encrypted_hex = b'd534bb96d3be74401001205b0d6567aa'

    return encrypted_base64

output = _encrypt(data)

节点 v6.10.0

let crypto = require("crypto");
let enc = require("./encryption");

var key = 'key-xxxxxxxxxxxxxxxxxxZZ';
var iv = '1234567812345678';
var data = 'some_secret_data';

var encrypted_hex = encrypt(data, 'hex');
var encrypted_base64 = encrypt(data, 'base64');

console.log(encrypted_hex);
// encrypted_hex = 'd534bb96d3be74401001205b0d6567aab4c31f7a76936598e5a1cc05385f3a91'

console.log(encrypted_base64);
// encrypted_base64 = '1TS7ltO+dEAQASBbDWVnqrTDH3p2k2WY5aHMBThfOpE='

function encrypt(msg, encoding){
    var aes = crypto.createCipheriv('aes-192-cbc', key, iv);
    var crypted = aes.update(msg,'utf8', encoding)
    crypted += aes.final(encoding);

    return crypted;
}

正如您在上面看到的,Python 产生的encrypted_hex 等于d534bb96d3be74401001205b0d6567aa。在 Node 中,encrypted_hex 包含上面提到的值 + b4c31f7a76936598e5a1cc05385f3a91

谁能帮我理解这里发生了什么: 为什么 Node.js 产生的结果要长两倍?

【问题讨论】:

  • 由于您在节点中指定 AES 192,是否有可能您的密钥大小不匹配,因此您的密钥在 python 中较小(例如,128)并且节点用空白填补了空白?只是一个想法。

标签: python node.js encryption aes pycrypto


【解决方案1】:

我想通了。 这是因为 Pythons 的 PyCrypto 包和 Nodes 的 Crypto 模块的行为不同。我正在使用 AES,因为它是一个块密码,它要求数据以指定长度的块的形式出现。

如果 PyCrypto 遇到不是 16 位块的数据,它就会失败。 Nodes 的 Crypto,默认情况下会填充数据,因此数据总是以大块的形式出现。

为简单起见,我在上面的示例中测试了长度为 16 字节的数据。那么为什么结果不一样呢?

Python 模块默认没有填充数据,因为数据包含正确的长度,所以我们得到了预期的结果。

然而,Node Crypto 模块确实填充了数据,并且显然将整个 16 位填充块添加到原始消息中(这听起来确实像一个错误)。这就是为什么加密节点的消息的第一部分对应于在 Python 中创建的消息,另一部分只是 Node Crypto 试图加密自己的过多填充。

无论如何,为了摆脱错误,我只是添加了

 aes.setAutoPadding(false);

在我的encrypt() 函数中。

哇哦。

【讨论】:

  • 请不要禁用填充。你真的应该在 Python 中启用填充和implement
猜你喜欢
  • 2016-09-23
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
相关资源
最近更新 更多