node.js - Node.js 中的 AEAD AES-256-GCM
问题描述
如何使用 Node.js 解密其他语言加密的数据?为了描述这个问题,我们用 Python 编写了一些代码:
plain_text = 'some data'
nonce = 'some nonce string'
associated_data = 'some associated data'
key = '--- 32 bytes secret key here ---'
在python中加密
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
aesgcm = AESGCM(key.encode())
encrypted = aesgcm.encrypt(nonce.encode(), plain_text.encode(), associated_data.encode())
print(aesgcm.decrypt(nonce.encode(), encrypted, associated_data.encode()))
ciphertext = base64.b64encode(encrypted)
解决方案
在 Node.js 中解密,我们不需要额外的依赖。
crypto 模块实现了 GCM 算法,但概念不同。
const crypto = require('crypto')
encrypted = Buffer.from(ciphertext, 'base64')
let decipher = crypto.createDecipheriv('AES-256-GCM', key, nonce)
decipher.setAuthTag(encrypted.slice(-16))
decipher.setAAD(Buffer.from(associated_data))
let output = Buffer.concat([
decipher.update(encrypted.slice(0, -16)),
decipher.final()
])
console.log(output.toString())
推荐阅读
- c# - 在 UWP 中创建/编写/压缩/解压缩文件
- vba - 在 2 个不同的行中查找匹配项 - IF Else 失败
- python - 如何通过多个规则加快形成新列
- javascript - 如何撤消 $("button").remove()?
- mysql - MySQL依靠前提条件?
- python - Windows 10、Python 3.6 和 64 位上的 TensorFlow 加载 DLL 失败
- android - 我可以通过始终在后台运行的服务跟踪 gps 纬度和经度吗?
- php - 加密的 zip 文件,在 php 7.2 之前
- javascript - 使用 SimpleHTMLDom 从 javascript var 解析
- c++ - 如何在我的 Visual C++ 项目中使用 .a 文件