เมธอด decipher.final() ใช้สำหรับคืนค่าบัฟเฟอร์หรือสตริงที่มีค่าของออบเจ็กต์ decipher เป็นหนึ่งในเมธอดในตัวที่จัดเตรียมโดยคลาส Cipher ภายในโมดูล crypto เมธอด decipher ไม่สามารถใช้ถอดรหัสข้อมูลได้อีกหลังจากที่เรียก decipher.final() แล้ว การเรียก cipher.final() มากกว่าหนึ่งครั้งจะข้อกลับข้อผิดพลาด
ไวยากรณ์
decipher.final([outputEncoding])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายดังนี้:
outputEncoding – รับการเข้ารหัสเอาต์พุตเป็นพารามิเตอร์ ประเภทอินพุตเป็นสตริง ค่าที่เป็นไปได้: hex, base64 ฯลฯ
ตัวอย่าง
สร้างไฟล์ชื่อ decipherFinal.js และคัดลอกโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ใช้คำสั่งต่อไปนี้เพื่อรันโค้ด:
node decipherFinal.js
decipherFinal.js
// ตัวอย่างสาธิตการใช้เมธอด cipher.final()
// นำเข้าโมดูล crypto
const crypto = require('crypto');
// กำหนดอัลกอริทึม AES
const algorithm = 'aes-192-cbc';
// กำหนดรหัสผ่านที่ใช้สร้างกุญแจ
const password = '12345678123456789';
// ดึงกุญแจสำหรับออบเจ็กต์ decipher
const key = crypto.scryptSync(password, 'old data', 24);
// กำหนด IV แบบคงที่
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// กำหนดออบเจ็กต์ 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');
// แสดงผลลัพธ์
console.log("Decrypted value -- " + decryptedValue1);
// console.log("Base64 String:- " + base64Value)
ผลลัพธ์
C:\home\node>> node decipherFinal.js Decrypted value -- Welcome to tutorials point
ตัวอย่างเพิ่มเติม
ลองดูตัวอย่างอีกหนึ่งกรณี:
// ตัวอย่างสาธิตการใช้เมธอด cipher.final()
// นำเข้าโมดูล crypto
const crypto = require('crypto');
// กำหนดอัลกอริทึม AES
const algorithm = 'aes-192-cbc';
// กำหนดรหัสผ่านที่ใช้สร้างกุญแจ
const password = '12345678123456789';
// ดึงกุญแจสำหรับออบเจ็กต์ decipher
const key = crypto.scryptSync(password, 'old data', 24);
// กำหนด IV แบบคงที่
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// กำหนดออบเจ็กต์ cipher เพื่อถอดรหัส
const encrypted = 'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';
// const encrypted2 = '8d11772fce59f08e7558db5bf17b3112';
var buf = [];
// อัปเดตข้อมูล decipher
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
// ใส่ข้อมูลลงบัฟเฟอร์หลังถอดรหัส
buf.push(decrypted);
buf.push(decipher.final('utf8'));
// แสดงผลลัพธ์
console.log(buf.join(' '));
ผลลัพธ์
C:\home\node>> node decipherFinal.js Welcome to tutor ials point