Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức decipher.update() trong Node.js


Phương thức decipher.update() dùng để cập nhật decipher với dữ liệu nhận được theo định dạng mã hóa cho trước. Đây là phương thức nội bộ của lớp Decipher trong module crypto. Nếu chỉ định inputEncoding, tham số data là chuỗi, ngược lại là buffer.

Cú pháp

decipher.update(data, [inputEncoding], [outputEncoding])

Tham số

  • data – Dữ liệu đầu vào để cập nhật decipher.

  • inputEncoding – Mã hóa đầu vào: hex, base64, v.v.

  • outputEncoding – Mã hóa đầu ra: hex, base64, v.v.

Ví dụ

Tạo file decipherUpdate.js và sao chép mã. Chạy lệnh:

node decipherUpdate.js

decipherUpdate.js

// Ví dụ minh họa decipher.update()
// Import module crypto
const crypto = require('crypto');

// Khởi tạo thuật toán AES
const algorithm = 'aes-192-cbc';
// Khởi tạo mật khẩu
const password = '12345678123456789';
// Tạo khóa cho decipher
const key = crypto.scryptSync(password, 'old data', 24);
// Khởi tạo iv tĩnh
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Dữ liệu mã hóa
const encrypted = '083bfe1b2f91677e5d00add115be2f1b2e362e190406f5c6b60e86969bf03bff';

// Cập nhật decipher
let decryptedValue = decipher.update(encrypted, 'hex', 'utf8');
decryptedValue += decipher.final('utf8');

// In kết quả
console.log("Giá trị giải mã -- " + decryptedValue);

Kết quả

C:\home\node>> node decipherUpdate.js
Giá trị giải mã -- Some new text data

Ví dụ 2

Ví dụ dùng scrypt bất đồng bộ.

// Ví dụ minh họa decipher.update()
// Import module crypto
const crypto = require('crypto');

// Khởi tạo thuật toán AES
const algorithm = 'aes-192-cbc';
// Khởi tạo mật khẩu
const password = '12345678123456789';
// Tạo khóa bất đồng bộ
crypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => {
    if (err) throw err;
    // iv tĩnh
    const iv = Buffer.alloc(16, 0);
    // Tạo decipher
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    const encrypted = '91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074';
    // Lấy chuỗi giải mã
    const decrypted = decipher.update(encrypted, 'hex', 'utf8');
    // In kết quả
    console.log("Giá trị giải mã:- " + decrypted);
});

Kết quả

C:\home\node>> node decipherUpdate.js
Giá trị giải mã:- Some new text data