//直接上代码上说明
const crypto = require('crypto');
class Cipher {
//设置私有成员,#key随机的加密密码,#iv加密时所用的初始向量
#key = crypto.randomBytes(32); // 256-bit key
#iv = crypto.randomBytes(12); // 96-bit IV
constructor(aad) {
//设置附加的认证数据,任何字符
this.aad = Buffer.from(aad); // 附加认证数据
}
//加密
encrypt(text) {
//创建加密实例,经过身份验证的加密模式,就是认证数据(当前支持 GCM、CCM、OCB 和 chacha20-poly1305)
const cipher = crypto.createCipheriv('aes-256-gcm', this.#key, this.#iv);
cipher.setAAD(this.aad);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag(); // 获取认证标签
return { encrypted, authTag }; // 返回密文和认证标签
}
//解密
decipher(encrypted, authTag) {
const decipher = crypto.createDecipheriv('aes-256-gcm', this.#key, this.#iv);
//解密也需要认证标签
decipher.setAAD(this.aad);
decipher.setAuthTag(authTag); // 设置认证标签
try {
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (err) {
console.error('Decryption failed:', err.message);
return null;
}
}
}
// 使用示例
const c = new Cipher('metadata');
const { encrypted, authTag } = c.encrypt('hello'); // 加密
console.log('Encrypted:', encrypted);
console.log('Auth Tag:', authTag.toString('hex'));
const decrypted = c.decipher(encrypted, authTag); // 解密
console.log('Decrypted:', decrypted);