📜  Node.js cipher.final() 方法(1)

📅  最后修改于: 2023-12-03 15:33:08.415000             🧑  作者: Mango

Node.js cipher.final() 方法

在 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
备注
  • cipher.final() 方法只能被调用一次,且必须在加密过程中调用。
  • 输出格式可以是 buffer 对象、hex 编码、base64 编码等,如果设置了 outputEncoding 参数则返回相应格式的字符串,否则返回 buffer 对象。
参考链接