A piece of code is currently executing on an online compiler utilizing Node 12.16.1 with smooth operation and no errors. This code snippet originally belonged to a different project, hence additional context has been provided.
Output:
Create a 32-byte AES key using PBKDF2
aesKeySha256 length: 32 data: e1ea3e4b0376c0f9bf93b94fe71719a099317297b79108aacd88c8a355d7a3d4
aesKeySha1 length: 32 data: d6bc1ae2aea28f5098826b555d7a0fe073e5bc7d8136d232e01d422ba2dd761e
aesKeySha1 Base64: 1rwa4q6ij1CYgmtVXXoP4HPlvH2BNtIy4B1CK6Lddh4=
Note on Security: The following code incorporates a fixed salt - for live deployment, ensure to use a randomly generated salt for each execution:
console.log("Create a 32-byte long AES key using PBKDF2");
var crypto = require('crypto');
var password = "secret password";
var PBKDF2_ITERATIONS = 15000; // the higher number of iterations, the better but slower
// ### Security Notification: Never utilize a fixed salt in production environments, reserved for comparative purposes only
var salt = generateFixedSalt32Byte();
// Kindly make use of the function generateSalt32Byte() below instead
// var salt = generateSalt32Byte();
var aesKeySha256 = generateAes256KeyPbkdf2Sha256(password, PBKDF2_ITERATIONS, salt);
console.log('aesKeySha256 length: ',
aesKeySha256.length, ' data: ', bytesToHex(aesKeySha256));
var aesKeySha1 = generateAes256KeyPbkdf2Sha1(password, PBKDF2_ITERATIONS, salt);
console.log('aesKeySha1 length: ',
aesKeySha1.length, ' data: ', bytesToHex(aesKeySha1));
var aesKeySha1Base64 = generateAes256KeyPbkdf2Sha1Base64(password, PBKDF2_ITERATIONS, salt);
console.log('aesKeySha1 Base64: ', aesKeySha1Base64);
function generateAes256KeyPbkdf2Sha256(password, iterations, salt) {
return crypto.pbkdf2Sync(password, salt, iterations, 32, 'sha256');
}
function generateAes256KeyPbkdf2Sha1(password, iterations, salt) {
return crypto.pbkdf2Sync(password, salt, iterations, 32, 'sha1');
}
function generateAes256KeyPbkdf2Sha1Base64(password, iterations, salt) {
return crypto.pbkdf2Sync(password, salt, iterations, 32, 'sha1').toString('base64');
}
function generateSalt32Byte() {
return crypto.randomBytes(32);
}
function generateFixedSalt32Byte() {
return Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex');
}
function bytesToHex(input) {
return input.toString('hex');
}