Node.js 中的 cipher.final() 方法

node.jsjavascriptweb developmentfront end technology

cipher.final() 用于返回包含密码对象值的缓冲区或字符串。它是 crypto 模块中的 Cipher 类提供的内置方法之一。如果指定了输出编码,则返回字符串。如果未指定输出编码,则返回缓冲区。多次调用 cipher.final 方法将引发错误。

语法

cipher.final([outputEncoding])

参数

上述参数描述如下 −

  • outputEncoding – 它将输出编码作为参数。此参数的输入类型为字符串。可能的输入值为 hex、base64 等。

示例

创建一个名为 – cipherFinal.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −

node cipherFinal.js

cipherFinal.js

// 示例演示如何使用 cipher.final() 方法

// 导入 crypto 模块
const crypto = require('crypto');

// 初始化 AES 算法
const algorithm = 'aes-192-cbc';
// 初始化用于生成密钥的密码
const password = '12345678';

// 检索密码对象的密钥
const key = crypto.scryptSync(password, 'salt', 24);

// 初始化静态 iv
const iv = Buffer.alloc(16, 0);

// 初始化密码对象以获取密码
const cipher = crypto.createCipheriv(algorithm, key, iv);
const cipher2 = crypto.createCipheriv(algorithm, key, iv);

//获取定义 outputEncoding 后的字符串值
let hexValue = cipher.final('hex');
let base64Value = cipher2.final('base64');

// 打印结果...
console.log("Hex String:- " + hexValue);
console.log("Base64 String:- " + base64Value)

输出

C:\home
ode>> node cipherFinal.js Hex String:- 8d11772fce59f08e7558db5bf17b3112 Base64 String:- jRF3L85Z8I51WNtb8XsxEg==

示例

我们再看一个例子。

// 示例演示 cipher.final() 方法的使用

// 导入 crypto 模块
const crypto = require('crypto');

// 初始化 AES 算法
const algorithm = 'aes-192-cbc';

// 初始化用于生成密钥的密码
const password = '12345678';

// 检索密码对象的密钥
const key = crypto.scryptSync(password, 'salt', 24);

crypto.scrypt(password, 'salt', 24,
   { N: 512 }, (err, key) => {

      if (err) throw err;

   // 初始化静态 iv
   const iv = Buffer.alloc(16, 0);

   // 初始化密码对象以获取密码
   const cipher = crypto.createCipheriv(algorithm, key, iv);

   // 由于输出编码为空,因此获取缓冲区值
   let hexValue = cipher.final();
   let base64Value = cipher.final('base64');

   // 打印结果...
   console.log("Buffer:- " + hexValue);
   console.log("Base64 String:- " + base64Value)
});

输出

C:\home
ode>> node cipherFinal.js internal/crypto/cipher.js:164    const ret = this._handle.final();                            ^ Error: Unsupported state    at Cipheriv.final (internal/crypto/cipher.js:164:28)    at Object. (/home/node/test/cipher.js:22:26)    at Module._compile (internal/modules/cjs/loader.js:778:30)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)    at Module.load (internal/modules/cjs/loader.js:653:32)    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)    at Function.Module._load (internal/modules/cjs/loader.js:585:3)    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)    at startup (internal/bootstrap/node.js:283:19)    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

在上面的例子中,我们得到错误是因为我们已经得到了该密钥的密码。由于这是最终方法,因此当我们再次尝试找出同一密钥的密码时会出错。


相关文章