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

เมธอด crypto.createCipheriv() ใน Node.js

เมธอด crypto.createCipheriv() สร้างและคืนค่า cipher object ตามอัลกอริทึม key และ initialization vector (iv) ที่ระบุ ใช้สำหรับการเข้ารหัสข้อมูล

ไวยากรณ์

crypto.createCipheriv(algorithm, key, iv, options)

พารามิเตอร์

  • algorithm – อัลกอริทึม เช่น aes-256-cbc, aes-192-cbc
  • key – raw key สำหรับอัลกอริทึม (string, Buffer, TypedArray, DataView, หรือ KeyObject)
  • iv – initialization vector ทำให้ cipher ไม่ซ้ำกัน (string, Buffer, TypedArray, DataView, หรือ null)
  • options – ตัวเลือกควบคุมสตรีม (บังคับเมื่อใช้โหมด CCM หรือ OCB เช่น aes-256-ccm)

ตัวอย่าง: เข้ารหัสด้วย AES-256-CBC

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}

var output = encrypt("TutorialsPoint");
console.log(output);

ผลลัพธ์

{ iv: '3dd899aa441c00d4d8d2ff95abb2e684', encryptedData: 'b4985053bc1507fc25a4d99823dc8b03' }

ตัวอย่าง: ใช้ scryptSync สร้าง key จาก password

const crypto = require('crypto');

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

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = '';

cipher.on('readable', () => {
  let chunk;
  while (null !== (chunk = cipher.read())) {
    encrypted += chunk.toString('base64');
  }
});

cipher.on('end', () => {
  console.log(encrypted);
});

cipher.write('TutorialsPoint');
cipher.end();
console.log("Completed... !");

ผลลัพธ์

Completed... !
uqeQEkXy5dpJjQv+JDvMHw==