Node.js 中的 cipher.final() 方法
所述用于返回包含加密对象的值的缓冲或字符串。它是加密模块中的类Cipher提供的内置方法之一。如果指定了输出编码,则返回一个字符串。如果未指定输出编码,则返回缓冲区。多次调用该方法将引发错误。cipher.final()cipher.final
语法
cipher.final([outputEncoding])
参数
上述参数描述如下-
outputEncoding –它将输出编码作为参数。此参数的输入类型是字符串。可能的输入值为十六进制、base64等。
示例
创建一个具有名称的文件-cipherFinal.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示-
node cipherFinal.js
cipherFinal.js
//演示cipher.final()方法使用的示例
//导入加密模块
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\node>> node cipherFinal.js Hex String:- 8d11772fce59f08e7558db5bf17b3112 Base64 String:- jRF3L85Z8I51WNtb8XsxEg==
示例
让我们再看一个例子。
//演示cipher.final()方法使用的示例
//导入加密模块
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\node>> node cipherFinal.js
internal/crypto/cipher.js:164
const ret = this._handle.final();
^
Error: Unsupported state
atCipheriv.final(internal/crypto/cipher.js:164:28)
at Object. (/home/node/test/cipher.js:22:26)
atModule._compile(internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
atModule.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)在上面的示例中,我们收到错误,因为我们已经获得了该密钥的密码。由于它是最终方法,因此当我们再次尝试找出相同密钥的密码时会出错。