เมธอด decipher.update() ใช้สำหรับอัปเดต decipher ด้วยข้อมูลที่ได้รับตามรูปแบบการเข้ารหัสที่กำหนด เป็นหนึ่งในเมธอดในตัว (built-in method) ที่จัดเตรียมโดยคลาส Decipher ภายในโมดูล crypto หากระบุการเข้ารหัสอินพุต (input encoding) อาร์กิวเมนต์ data จะเป็นสตริง มิฉะนั้นอาร์กิวเมนต์ data จะเป็นบัฟเฟอร์ (buffer)
ไวยากรณ์
decipher.update(data, [inputEncoding], [outputEncoding])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายดังนี้:
data – รับข้อมูลเป็นอินพุตที่ส่งผ่านเพื่ออัปเดตเนื้อหา decipher
inputEncoding – รับการเข้ารหัสอินพุตเป็นพารามิเตอร์ ค่าที่เป็นไปได้: hex, base64 ฯลฯ
outputEncoding – รับการเข้ารหัสเอาต์พุตเป็นพารามิเตอร์ ประเภทอินพุตเป็นสตริง ค่าที่เป็นไปได้: hex, base64 ฯลฯ
ตัวอย่าง
สร้างไฟล์ชื่อ decipherUpdate.js และคัดลอกโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ใช้คำสั่งต่อไปนี้เพื่อรันโค้ด:
node decipherUpdate.js
decipherUpdate.js
// ตัวอย่างสาธิตการใช้เมธอด decipher.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);
// กำหนดออบเจ็กต์ decipher เพื่อถอดรหัส
const encrypted = '083bfe1b2f91677e5d00add115be2f1b2e362e190406f5c6b60e86969bf03bff';
// const encrypted2 = '8d11772fce59f08e7558db5bf17b3112';
let decryptedValue = decipher.update(encrypted, 'hex', 'utf8');
// let decryptedValue1 = decipher.update(encrypted1, 'hex', 'utf8');
decryptedValue += decipher.final('utf8');
// แสดงผลลัพธ์
console.log("Decrypted value -- " + decryptedValue);
// console.log("Base64 String:- " + base64Value)
ผลลัพธ์
C:\home\node>> node decipherUpdate.js Decrypted value -- Some new text data
ตัวอย่างเพิ่มเติม
ลองดูตัวอย่างอีกหนึ่งกรณี:
// ตัวอย่างสาธิตการใช้เมธอด decipher.final()
// นำเข้าโมดูล crypto
const crypto = require('crypto');
// กำหนดอัลกอริทึม AES
const algorithm = 'aes-192-cbc';
// กำหนดรหัสผ่านที่ใช้สร้างกุญแจ
const password = '12345678123456789';
// ดึงกุญแจสำหรับออบเจ็กต์ decipher แบบอะซิงโครนัส
crypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => {
if (err) throw err;
// กำหนด IV แบบคงที่
const iv = Buffer.alloc(16, 0);
// กำหนด decipher ด้วยอัลกอริทึม กุญแจ และ IV
const decipher = crypto.createDecipheriv(algorithm, key, iv);
const encrypted = '91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074';
// ดึงค่าสตริงที่ถอดรหัสแล้ว
const decrypted = decipher.update(encrypted, 'hex', 'utf8');
// แสดงผลลัพธ์
console.log("Decrypted value:- " + decrypted);
});
ผลลัพธ์
C:\home\node>> node decipherUpdate.js Decrypted value:- Some new text data