【发布时间】:2019-10-18 03:20:26
【问题描述】:
尝试从 Python 到 Nodejs 实现这 2 个函数:
def encrypt(base64_data):
key = os.urandom(32)
encoded_key = base64.b16encode(key)
iv = ""
iv_vector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in iv_vector:
iv += chr(i)
ctr = Counter.new(128, initial_value=long(iv.encode("hex"), 16))
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
encrypted = cipher.encrypt(base64_data)
return encrypted, encoded_key
def decrypt(encrypted_data, orig_key):
key = base64.b16decode(orig_key)
iv = ""
iv_vector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in iv_vector:
iv += chr(i)
ctr = Counter.new(128, initial_value=long(iv.encode("hex"), 16))
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
decrypted = cipher.decrypt(encrypted_data)
return decrypted
此解密有效(当我在 Python 中加密时,我设法在节点中解密),但相反的方式失败了。 知道 nodejs 加密功能中缺少什么吗?
// Not working
export const encrypt = (base64Data: string): {encryptedData: string, decryptionKey: string} => {
const key = randomBytes(32);
const encodedKey = key.toString('hex');
var iv = Buffer.from('00000000000000000000000000000000', 'hex');
var encipher = createCipheriv('aes-256-ctr', key, iv);
const x = Buffer.concat([
encipher.update(base64Data),
encipher.final()
]);
return {encryptedData: x.toString('base64'), decryptionKey: encodedKey};
}
// This works
export const decrypt = (base64Data: string, encodedKey: string) => {
const key = Buffer.from( encodedKey, 'hex')
var iv = Buffer.from('00000000000000000000000000000000', 'hex');
var decipher = createDecipheriv('aes-256-ctr', key, iv);
return Buffer.concat([
decipher.update(Buffer.from(base64Data)),
decipher.final()
]);
}
【问题讨论】:
-
您是否检查过 Python 的
decrypt与 Python 的encrypt以及 node.js 中的相同? -
Python enc->dec 有效。节点 enc->dec 失败。 Python enc->Node dec 工作.....
-
@MTZ4 你能发布你最终是如何让它工作的吗?
-
@FilipePereira 将
const key = randomBytes(32); const encodedKey = key.toString('hex')替换为const encodedKey = randomBytes(32); const key = Buffer.from( encodedKey, 'hex')。还要确保你所有的 IO 都被正确解析......(加密之前和之后)!
标签: python node.js encryption