Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

aes gcm - AEAD AES-256-GCM in Node.js

How to decrypt data encrypted by other languages with Node.js? To describe the problem, we write some code in Python:

plain_text = 'some data'
nonce = 'some nonce string'
associated_data = 'some associated data'
key = '--- 32 bytes secret key here ---'

encrypting in 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Decrypting in Node.js, we don't need additional dependencies.

The crypto module has implemented GCM algorithm, but it is different in concept.

    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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...