【问题标题】:Decrypting ChaCha20-Poly1305 binary data in NodeJS that was encrypted in python application from a string从字符串中解密在 Python 应用程序中加密的 NodeJS 中的 ChaCha20-Poly1305 二进制数据
【发布时间】:2021-08-10 04:14:05
【问题描述】:

我们有一个 Python 应用程序将字符串作为加密二进制数据存储在 MongoDB 中,它使用

from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305

在 NodeJS 方面,我一直无法弄清楚如何解密数据,我有我们的盐,我们的密钥,但据我所知,没有 IV,或者 python 模块可能只是隐藏了所有在底层,所有 python 应用程序所要做的就是调用 encrypt(value, salt) 和 decrypt(value, salt)

Python:

class ChaChaEncryptedStringField(EncryptedStringField):
"""
A field which, given an encryption key and salt, will automatically encrypt/decrypt
sensitive data to avoid needing to do this before passing in. This encryption
method reliably produces a searchable string.
"""

def __init__(self, key, salt, *args, **kwargs):
    """Initialize the ChaChaEncryptedStringField.
    Args:
        key (str) -
        salt (str) -
    """
    class Hook:
        def __init__(self, key, salt):
            self.salt = salt
            self.chacha = ChaCha20Poly1305(key)

        def encrypt(self, value):
            return self.chacha.encrypt(self.salt, value, None)

        def decrypt(self, value):
            return self.chacha.decrypt(self.salt, value, None)

    self.encryption_hook = Hook(b64decode(key), b64decode(salt))
    super(EncryptedStringField, self).__init__(*args, **kwargs)

Javascript(不起作用但关闭):

const authTagLocation = data.buffer.length - 16;
const ivLocation = data.buffer.length - 28;
const authTag = data.buffer.slice(authTagLocation);
const iv = data.buffer.slice(ivLocation, authTagLocation);
const encrypted = data.buffer.slice(0, ivLocation);
const decipher = crypto.createDecipheriv('chacha20-poly1305', keyBuffer, iv,{ authTagLength: 16 } );
let dec = decipher.update(
  data.buffer, 'utf-8', 'utf-8'
);
dec += decipher.final('utf-8');

return dec.toString();

经过一些研究和反复试验,我抱怨 IV 不正确,密钥长度正确,但仍然得到乱码数据

所以我实际上得到了以下代码,但我不会声称完全理解正在发生的事情:

工作 Javascript(从秘密中提取盐,使用提取的 IV 失败)

const authTagLength = 16
const authTagLocation = data.buffer.length - authTagLength;
const ivLocation = data.buffer.length - 16;
const authTag = data.buffer.slice(authTagLocation);
const iv = data.buffer.slice(ivLocation, authTagLocation);
const encrypted = data.buffer.slice(0, ivLocation);

const decipher = crypto.createDecipheriv('chacha20-poly1305', keyBuffer, saltBuffer,{ authTagLength: authTagLength } );
let dec = decipher.update(
  encrypted, 'utf-8', 'utf-8'
);
dec += decipher.final('utf-8');

return dec.toString();

【问题讨论】:

  • 您应该真正包含原始代码以及您到目前为止所尝试的内容。

标签: python node.js encryption node-crypto python-cryptography


【解决方案1】:

Python 代码中所谓的 salt 实际上是 nonce(或 IV),请参阅 ChaCha20Poly1305Cryptography 文档) .解释了 nonce 和 salt 之间的区别,例如here。在下文中,我使用术语 nonce。

在 NodeJS 代码中,密文和标签的分离以一种过于复杂的方式执行,但(巧合地)产生了正确的结果。 IV 在分离中不起作用。标记是最后16个字节,实际密文是标记前的剩余数据。

此外,目前没有进行身份验证,这是不安全的。要启用身份验证,必须在调用final() 之前使用setAuthTag() 设置标记。如果认证失败,则抛出异常。

以下示例显示了用于解密的可能 NodeJS 实现。密文是使用发布的 Python 代码生成的:

const crypto = require('crypto');

const keyBuffer = Buffer.from('MDEyMzQ1Njc4OTAxMjM0NTAxMjM0NTY3ODkwMTIzNDU=', 'base64');
const nonceBuffer = Buffer.from('MDEyMzQ1Njc4OTAx', 'base64')
const dataBuffer = Buffer.from('4bAaXOlQGhLI3tAsJju0e8Z737eF683Izik+6Uz4axPKj6NbmGLXcCgxukIyo8whOsu2lEgg3llInLA=', 'base64')

const authTagLength = 16
const encrypted = dataBuffer.slice(0, -authTagLength)
const tag = dataBuffer.slice(-authTagLength);

const decipher = crypto.createDecipheriv('chacha20-poly1305', keyBuffer, nonceBuffer, {authTagLength: authTagLength});
decipher.setAuthTag(tag)

let decrypted;
try {
    decrypted = decipher.update(encrypted, '', 'utf-8');
    decrypted += decipher.final('utf-8');
    console.log(decrypted);
} catch(e) {
    console.log("Decryption failed!");
}

请注意 Python 代码中的以下漏洞:密钥和随机数在实例化时传递给 ChaChaEncryptedStringField 类。这导致使用此实例执行的所有加密都使用相同的密钥/IV 对,这是不安全的,请参阅here。正确的方法是为每个加密创建一个随机随机数。 nonce 不是秘密的,它与密文和标签一起传递,通常是串联的。

【讨论】:

  • 感谢@Topaco 与我的结论一致...我相信已决定不随机化 IV 以便能够对加密数据进行搜索?但我们稍后会进行重大重构来替换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
相关资源
最近更新 更多