當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js Decipher.final()用法及代碼示例

decipher.final() 用於返回包含解密對象值的緩衝區或字符串。它是加密模塊中的類 Cipher 提供的內置方法之一。一旦 decipher.final 方法被調用, decipher 方法就不能用於解密數據。多次調用 cipher.final 方法將引發錯誤。

用法

decipher.final([outputEncoding])

參數

上述參數描述如下 -

  • outputEncoding - 它將輸出編碼作為參數。此參數的輸入類型是字符串。可能的輸入值為十六進製、base64 等。

示例

創建一個名為 decipherFinal.js 的文件並複製以下代碼片段。創建文件後,使用以下命令運行此代碼,如下例所示 -

node decipherFinal.js

decipherFinal.js

// Example to demonstrate the use of cipher.final() method

// Importing the crypto module
const crypto = require('crypto');

// Initialising the AES algorithm
const algorithm = 'aes-192-cbc';
// Initialising the password used for generating key
const password = '12345678123456789';

// Retrieving key for the decipher object
const key = crypto.scryptSync(password, 'old data', 24);

// Initializing the static iv
const iv = Buffer.alloc(16, 0);

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Initializing the cipher object to get cipher
const encrypted1 =
'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';
// const encrypted2 = '8d11772fce59f08e7558db5bf17b3112';

let decryptedValue1 = decipher.update(encrypted1, 'hex', 'utf8');
// let decryptedValue1 = decipher.update(encrypted1, 'hex', 'utf8');

decryptedValue1 += decipher.final('utf8');

// Printing the result...
console.log("Decrypted value -- " + decryptedValue1);
// console.log("Base64 String:- " + base64Value)

輸出

C:\home\node>> node decipherFinal.js
Decrypted value -- Welcome to tutorials point

示例

讓我們再看一個例子。

// Example to demonstrate the use of cipher.final() method

// Importing the crypto module
const crypto = require('crypto');

// Initialising the AES algorithm
const algorithm = 'aes-192-cbc';
// Initialising the password used for generating key
const password = '12345678123456789';

// Retrieving key for the decipher object
const key = crypto.scryptSync(password, 'old data', 24);

// Initializing the static iv
const iv = Buffer.alloc(16, 0);

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Initializing the cipher object to get cipher
const encrypted =
'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';
// const encrypted2 = '8d11772fce59f08e7558db5bf17b3112';

var buf = [];

// Updating the decopher data
let decrypted = decipher.update(encrypted, 'hex', 'utf8');

// Pushinf the data into buffer after decryption
buf.push(decrypted);
buf.push(decipher.final('utf8'));

// Printing the result
console.log(buf.join(' '));

輸出

C:\home\node>> node decipherFinal.js
Welcome to tutor ials point

相關用法


注:本文由純淨天空篩選整理自Mayank Agarwal大神的英文原創作品 Decipher.final() Method in Node.js。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。