【发布时间】: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