【问题标题】:Translate encryption in python to node将python中的加密转换为节点
【发布时间】: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


【解决方案1】:

如果考虑到以下几点,这两种代码的加密和解密在我的机器上以所有可能的组合运行。

  • Node-code 必须在 2 处更改,以便加密和解密一致:在 encrypt 方法的 return-statement 中,'00'+encodedKey 必须替换为 ''+encodedKey,否则解密的密钥太长一个字节。在decrypt 方法的return 语句中,Buffer.from(base64Data) 必须替换为Buffer.from(base64Data, 'base64'),因为密文是 Base64 编码的。

  • Python 中的密文(由encrypt 返回,传递给decrypt)是一个字节数组。 Node中的密文(从encrypt返回,传递给decrypt)是一个Base64编码的字符串。因此,这里需要进行转换,例如在 Python 代码中。

  • Node 将键返回为带有小写字母的十六进制字符串,Python 需要大写字母。因此,此处需要进行适当的转换,例如在 Python 代码中。

【讨论】:

  • 非常感谢! '00' 无关紧要,但现在可以了 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多