1

我有这段需要翻译成nodejs的python代码。python代码使用来自加密的pycrypto。在 nodejs 方面,我使用的是本机加密模块。加密字符串之间似乎存在不匹配。

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import json

raw_key = [0x58, 0x86, 0x17, 0x6d, 0x88, 0x7c, 0x9a, 0xa0, 0x61, 0x1b, 0xbb, 0x3e, 0x20, 0x28, 0xa4, 0x5a]
key = str(bytearray(raw_key))

raw_iv =  [0x34, 0x2e, 0x17, 0x99, 0x6d, 0x19, 0x3d, 0x28, 0xdd, 0xb3, 0xa2, 0x69, 0x5a, 0x2e, 0x6f, 0x1b]
iv = str(bytearray(raw_iv))

text = json.dumps({ "a": 1, "b": 2 })

cryptor = AES.new(key, AES.MODE_CBC, iv)
length = 16
count = len(text)
add = length - (count % length)
text = text + ('\0' * add)
encrypted = cryptor.encrypt(text);
print b2a_hex(encrypted)

上面的python代码输出

5c72b1a394654b6dab9ea8fdd90fe56b92141d74cb32ac65ede4d3154801bb57

而下面的nodejs代码

const crypto = require('crypto');

const KEY = Buffer.from([0x58, 0x86, 0x17, 0x6d, 0x88, 0x7c, 0x9a, 0xa0, 0x61, 0x1b, 0xbb, 0x3e, 0x20, 0x28, 0xa4, 0x5a]);
const IV = Buffer.from([0x34, 0x2e, 0x17, 0x99, 0x6d, 0x19, 0x3d, 0x28, 0xdd, 0xb3, 0xa2, 0x69, 0x5a, 0x2e, 0x6f, 0x1b]);

const text = JSON.stringify({ a: 1, b: 2 });

const cipher = crypto.createCipheriv('aes-128-cbc', KEY, IV);
cipher.setAutoPadding(true);
const encrypted = Buffer.concat([cipher.update(text, 'utf-8'), cipher.final()]);
console.log(encrypted.toString('hex'));

输出

d6a0dbc6df2a1038036e4db985f9ca10

他们为什么不匹配?难道我做错了什么?

4

1 回答 1

2

这里有两个问题:

  1. Node 的自动填充是 PKCS 填充。您的 python 代码使用空字节进行填充,这是一种不同的格式。节点文档甚至明确提到禁用自动填充以使用空字节填充。

  2. JSON 在 node 和 python 之间的格式略有不同。JavascriptJSON.stringify()会删除所有不必要的空格,而 python 会留下一些空格(例如,在数组/对象中的元素之间)。最简单的解决方案可能是更改 python 代码以指定显式separators选项: json.dumps({ "a": 1, "b": 2 }, separators=(',', ':')),因为 javascriptJSON.stringify()在以这种方式更改格式时并不灵活。

下面的节点代码显示,通过匹配 JSON 输出使用适当的填充,您将获得与 python 相同的十六进制输出:

const crypto = require('crypto');

const KEY = Buffer.from([0x58, 0x86, 0x17, 0x6d, 0x88, 0x7c, 0x9a, 0xa0, 0x61, 0x1b, 0xbb, 0x3e, 0x20, 0x28, 0xa4, 0x5a]);
const IV = Buffer.from([0x34, 0x2e, 0x17, 0x99, 0x6d, 0x19, 0x3d, 0x28, 0xdd, 0xb3, 0xa2, 0x69, 0x5a, 0x2e, 0x6f, 0x1b]);

var text = '{"a": 1, "b": 2}';

const cipher = crypto.createCipheriv('aes-128-cbc', KEY, IV);
cipher.setAutoPadding(false);

var length = 16;
var count = Buffer.byteLength(text);
var add = length - (count % length);
if (add > 0)
  text += '\0'.repeat(add);

const encrypted = Buffer.concat([cipher.update(text, 'utf-8'), cipher.final()]);
console.log(encrypted.toString('hex'));
于 2017-07-21T04:26:34.203 回答