Mô tả
Phương thức cipher.update() dùng để cập nhật cipher với dữ liệu nhận được theo định dạng encoding cho trước. Đây là một trong những phương thức built-in do class Cipher trong module crypto cung cấp. Nếu input encoding được chỉ định, đối số data là một string, ngược lại data là một buffer.
Cú pháp
cipher.update(data, [inputEncoding], [outputEncoding])
Tham số
data – Nhận dữ liệu đầu vào để cập nhật nội dung cipher.
inputEncoding – Nhận input encoding làm tham số. Các giá trị có thể: hex, base64, v.v.
outputEncoding – Nhận output encoding làm tham số. Kiểu đầu vào cho tham số này là string. Các giá trị có thể: hex, base64, v.v.
Ví dụ
Tạo file tên cipherUpdate.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
node cipherUpdate.js
cipherUpdate.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 cipher object const key = crypto.scryptSync(password, 'old data', 24); // Initializing the static iv const iv = Buffer.alloc(16, 0); // Initializing the cipher object to get cipher const cipher = crypto.createCipheriv(algorithm, key, iv); //Getting the updated string value with new data let updatedValue = cipher.update('Welcome to tutorials point', 'utf8', 'hex'); //Adding the old value and updated value updatedValue += cipher.final('hex'); // Printing the result... console.log("Updated String:- " + updatedValue);Đầu ra
C:\home\node>> node cipherUpdate.js Updated String:- a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a
Ví dụ khác
Xem thêm một ví dụ nữa.
// 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 cipher object crypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => { if (err) throw err; // Initializing the static iv const iv = Buffer.alloc(16, 0); // Initializing the cipher object to get cipher const cipher = crypto.createCipheriv(algorithm, key, iv); //Getting the updated string value with new data let updatedValue = cipher.update('Some new text data', 'utf8', 'hex'); //Adding the old value and updated value updatedValue += cipher.final('hex'); // Printing the result... console.log("Updated String:- " + updatedValue); });Đầu ra
C:\home\node>> node cipherUpdate.js Updated String:- 91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074