Phương thức decipher.final() trả về buffer hoặc chuỗi chứa giá trị cuối cùng của đối tượng decipher. Đây là phương thức nội bộ của lớp Cipher trong module crypto. Sau khi gọi decipher.final(), decipher không thể dùng để giải mã thêm dữ liệu. Gọi nhiều lần sẽ ném lỗi.
Cú pháp
decipher.final([outputEncoding])
Tham số
outputEncoding – Mã hóa đầu ra: hex, base64, v.v.
Ví dụ
Tạo file decipherFinal.js và sao chép mã. Chạy lệnh:
node decipherFinal.js
decipherFinal.js
// Ví dụ minh họa decipher.final()
// Import module crypto
const crypto = require('crypto');
// Khởi tạo thuật toán AES
const algorithm = 'aes-192-cbc';
// Khởi tạo mật khẩu
const password = '12345678123456789';
// Tạo khóa
const key = crypto.scryptSync(password, 'old data', 24);
// iv tĩnh
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// Dữ liệu mã hóa
const encrypted1 = 'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';
let decryptedValue1 = decipher.update(encrypted1, 'hex', 'utf8');
decryptedValue1 += decipher.final('utf8');
// In kết quả
console.log("Giá trị giải mã -- " + decryptedValue1);
Kết quả
C:\home\node>> node decipherFinal.js Giá trị giải mã -- Welcome to tutorials point
Ví dụ 2
Ví dụ dùng buffer để gộp kết quả.
// Ví dụ minh họa decipher.final()
// Import module crypto
const crypto = require('crypto');
// Khởi tạo thuật toán AES
const algorithm = 'aes-192-cbc';
// Khởi tạo mật khẩu
const password = '12345678123456789';
// Tạo khóa
const key = crypto.scryptSync(password, 'old data', 24);
// iv tĩnh
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// Dữ liệu mã hóa
const encrypted = 'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';
var buf = [];
// Cập nhật decipher
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
// Đẩy vào buffer
buf.push(decrypted);
buf.push(decipher.final('utf8'));
// In kết quả
console.log(buf.join(' '));
Kết quả
C:\home\node>> node decipherFinal.js Welcome to tutor ials point