gcm需要添加tag,可以自己拼接在加密后的数据后面,解密时自行分割后操作。tag为32位。
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';
const message = 'This is a secret message';
const iv = crypto.randomBytes(12);
const sKey = crypto.randomBytes(32);
const cipher = crypto.createCipheriv(algorithm, sKey, iv);
let encryptedData = cipher.update(message, 'utf-8', 'hex');
encryptedData += cipher.final('hex');
const authTag = cipher.getAuthTag().toString("hex"); // <- new
console.log({authTag, encryptedData}); // for debugging
const decipher = crypto.createDecipheriv(algorithm, sKey, iv);
decipher.setAuthTag(Buffer.from(authTag, 'hex')); // <- new
let decData = decipher.update(encryptedData, 'hex', 'utf-8');
decData += decipher.final('utf-8');
console.log('Decrypted message: ', decData)