Mô tả
Phương thức crypto.pbkdf2(), còn gọi là Password-Based Key Derivation function, cung cấp triển khai bất đồng bộ (asynchronous) của hàm dẫn xuất khóa. Một khóa được dẫn xuất bằng cách sử dụng Hmac digest của thuật toán xác định từ password, salt và iterations.
Cú pháp
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
Tham số
password – Mật khẩu để lấy khóa độ dài byte yêu cầu. Các giá trị có thể: string, DataView, Buffer, v.v.
salt – Tương tự password để lấy khóa. Các giá trị có thể: string, DataView, Buffer, v.v.
iterations – Lấy khóa mong muốn độ dài byte yêu cầu. Chấp nhận giá trị number.
keylen – Độ dài byte yêu cầu của khóa. Kiểu number.
digest – Thuật toán Hmac được chỉ định bởi giá trị digest này. Giá trị mặc định: 'sha1'.
callback – Nếu có lỗi xảy ra ở chế độ async, sẽ được xử lý trong callback.
Ví dụ
Tạo file tên pbkdf2.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
node pbkdf2.js
pbkdf2.js
// crypto.pbkdf2() demo example // Importing the crypto module const crypto = require('crypto'); // Defining the pbkdf2 with the following options crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; // Printing the derived key console.log("Key Derived: ",derivedKey.toString('hex')); });Đầu ra
C:\home\node>> node pbkdf2.js Key Derived: 3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e8 27304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae
Ví dụ khác
Xem thêm một ví dụ nữa.
// crypto.pbkdf2() demo example // Importing the crypto module const crypto = require('crypto'); // Defining the pbkdf2 with the following options crypto.pbkdf2('secret', 'salt', 100, 64, 'sha1', (err, derivedKey) => { if (err) throw err; // Printing the derived key console.log("Key Derived: ",derivedKey); console.log("Key Derived in hex: ",derivedKey.toString('hex')); console.log("Key Derived in base64: ",derivedKey.toString('base64')); });Đầu ra
C:\home\node>> node pbkdf2.js Key Derived:Key Derived in hex: b73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d3d2319132d84e1 91a783e200734e374a24b62cfab65dfb5e9dc28ae147072419 Key Derived in base64: tzY198CILh/Dum4psUrxJ034SCi00Y/MIi61dEVfUF09IxkTLYThkaeD4gBzTjdKJLYs+rZd+16dwo rhRwckGQ==