Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เมธอด cipher.final() ใน Node.js

เมธอด cipher.final() คืนค่า Buffer หรือ string ที่มีค่าสุดท้ายของ cipher object หากระบุ outputEncoding จะคืน string มิฉะนั้นคืน Buffer การเรียก cipher.final() ซ้ำจะโยนข้อผิดพลาด

ไวยากรณ์

cipher.final([outputEncoding])

พารามิเตอร์

  • outputEncoding – encoding ของผลลัพธ์ (เช่น hex, base64)

ตัวอย่าง: ใช้งานปกติ

const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = '12345678';
const key = crypto.scryptSync(password, 'salt', 24);
const iv = Buffer.alloc(16, 0);

const cipher = crypto.createCipheriv(algorithm, key, iv);
const cipher2 = crypto.createCipheriv(algorithm, key, iv);

let hexValue = cipher.final('hex');
let base64Value = cipher2.final('base64');

console.log("Hex String:- " + hexValue);
console.log("Base64 String:- " + base64Value);

ผลลัพธ์

Hex String:- 8d11772fce59f08e7558db5bf17b3112
Base64 String:- jRF3L85Z8I51WNtb8XsxEg==

ตัวอย่าง: เรียกซ้ำ (จะเกิด error)

crypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => {
  if (err) throw err;
  const iv = Buffer.alloc(16, 0);
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let hexValue = cipher.final();        // เรียกครั้งแรก
  let base64Value = cipher.final('base64'); // เรียกครั้งที่สอง -> Error
  console.log("Buffer:- " + hexValue);
  console.log("Base64 String:- " + base64Value);
});

ผลลัพธ์

Error: Unsupported state
at Cipheriv.final (internal/crypto/cipher.js:164:28)
...

เกิดข้อผิดพลาดเพราะเรียก final() ซ้ำบน cipher object เดียวกัน