เมธอด crypto.pbkdf2() ให้การทำงานแบบ asynchronous สำหรับ Password-Based Key Derivation Function 2 สร้างคีย์จาก password, salt, iterations ด้วย HMAC digest
ไวยากรณ์
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
พารามิเตอร์
- password – รหัสผ่าน
- salt – ค่า salt
- iterations – จำนวนรอบ
- keylen – ความยาวคีย์ (ไบต์)
- digest – อัลกอริทึม HMAC (ค่าเริ่มต้น: sha1)
- callback – callback function (err, derivedKey)
ตัวอย่าง: ใช้ SHA-512
const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log("Key Derived: ", derivedKey.toString('hex'));
});
ผลลัพธ์
Key Derived: 3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae
ตัวอย่าง: ใช้ SHA-1 แสดงหลาย encoding
crypto.pbkdf2('secret', 'salt', 100, 64, 'sha1', (err, derivedKey) => {
if (err) throw err;
console.log("Key Derived: ", derivedKey);
console.log("Key Derived (hex): ", derivedKey.toString('hex'));
console.log("Key Derived (base64): ", derivedKey.toString('base64'));
});
ผลลัพธ์
Key Derived:
Key Derived (hex): b73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d3d2319132d84e191a783e200734e374a24b62cfab65dfb5e9dc28ae147072419
Key Derived (base64): tzY198CILh/Dum4psUrxJ034SCi00Y/MIi61dEVfUF09IxkTLYThkaeD4gBzTjdKJLYs+rZd+16dworhRwckGQ==