📅  最后修改于: 2023-12-03 15:33:08.415000             🧑  作者: Mango
在 Node.js 中,cipher.final() 方法是 Cipher 类的一个函数,用于返回所有的加密数据。
cipher.final([outputEncoding])
outputEncoding
: 可选参数,指定加密数据的编码格式,默认值为 Buffer
。下面的例子演示了使用 AES 算法对字符串进行加密,并使用 cipher.final() 返回所有加密数据:
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = 'mysecretkey';
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello world!', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(`加密结果:${encrypted}`);
输出:
加密结果:2c083fedbba8d9a731e1e04771d3a931
buffer
对象、hex
编码、base64
编码等,如果设置了 outputEncoding
参数则返回相应格式的字符串,否则返回 buffer
对象。