Node.js 中的 AEAD AES-256-GCM

时间:2021-01-07 04:52:23

标签: node.js aes-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)

1 个答案:

答案 0 :(得分:1)

在 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())
相关问题