【发布时间】:2020-04-22 11:00:02
【问题描述】:
我一直无法让 Python 中的现有遗留代码像 NodeJS 一样加密/解密。我确实正确解码了前 16 个字符。
这是 Python 代码:
from Crypto.Cipher import AES
counter = b'HOJFKGQMRCTKUQHP'
cipher = AES.new(self.symmetric_key, AES.MODE_CTR, counter=lambda: counter)
encrypted = cipher.encrypt(data)
我发现每次迭代都使用相同的计数器的来源: PyCrypto problem using AES+CTR
在 NodeJS (ts-node) 中仅对前 16 个字符起作用是这样的:
import { createDecipheriv, Decipher } from 'crypto'
const decrypt = (inputBase64: string): string => {
const algorithm = 'aes-192-ctr'; // 24 byte key, 16 byte "counter"
var decipher: Decipher = createDecipheriv(algorithm, key, counter /* yes, it's an iv */)
// decipher.setAutoPadding(false);
return decipher.update(inputBase64, 'base64', 'utf8') + decipher.final('utf8');
}
我找到了各种在线资源,它们都增加了计数器 - 有没有办法使用内置的 Node 加密库来控制计数器的增量?我发现了一些我可以覆盖的在线实现(如果发生了这种情况): https://github.com/ricmoo/aes-js/blob/master/index.js#L656 https://github.com/brix/crypto-js/blob/develop/src/mode-ctr.js#L26
我怎样才能让它在 Node 中工作?我的 python 代码(这是遗留的,如果不迁移现有值就无法更改)具有以下输出:
encrypt('Testing--StackOverflow')
# outputs: 'r7G8gFNIHuY27nBjSo51nZ6mqZhVUQ=='
使用上述decrypt函数从节点:
const key = 'LKOXBRRUNBOSMENKEPPZUKWB';
const counter = 'HOJFKGQMRCTKUQHP';
const encrypted = 'r7G8gFNIHuY27nBjSo51nZ6mqZhVUQ==';
const clearText = decrypt(encrypted);
console.log('clear text:', clearText)
// outputs: clear text: Testing--StackOv�::��m
希望有人可以在这里分享一些见解!
【问题讨论】:
标签: python node.js encryption cryptography aes