cipher.update() ใช้เพื่ออัปเดตรหัสด้วยข้อมูลที่ได้รับตามรูปแบบการเข้ารหัสที่กำหนด เป็นหนึ่งในวิธีการ inbuilt ที่จัดเตรียมโดย class Cipher ภายในโมดูล crypto หากมีการระบุการเข้ารหัสอินพุต อาร์กิวเมนต์ data จะเป็นสตริง มิฉะนั้น อาร์กิวเมนต์ data จะเป็นบัฟเฟอร์
ไวยากรณ์
cipher.update(data, [inputEncoding], [outputEncoding])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายไว้ด้านล่าง −
-
ข้อมูล – ใช้ข้อมูลเป็นอินพุตที่ส่งผ่านเพื่ออัปเดตเนื้อหาการเข้ารหัส
-
การเข้ารหัสอินพุต – ใช้การเข้ารหัสอินพุตเป็นพารามิเตอร์ ค่าอินพุตที่เป็นไปได้ ได้แก่ hex, base64 เป็นต้น
-
การเข้ารหัสเอาต์พุต – ใช้การเข้ารหัสเอาต์พุตเป็นพารามิเตอร์ ประเภทอินพุตสำหรับพารามิเตอร์นี้คือสตริง ค่าอินพุตที่เป็นไปได้ ได้แก่ hex, base64 เป็นต้น
ตัวอย่าง
สร้างไฟล์ที่มีชื่อ – cipherUpdate.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −
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); ผลลัพธ์
C:\home\node>> node cipherUpdate.js Updated String:- a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a
ตัวอย่าง
ลองดูอีกตัวอย่างหนึ่ง
// 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);
}); ผลลัพธ์
C:\home\node>> node cipherUpdate.js Updated String:- 91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074