Skip to content

Instantly share code, notes, and snippets.

@ricpumanes
Forked from gibatronic/README.md
Created May 5, 2023 12:14
Show Gist options
  • Select an option

  • Save ricpumanes/12b82a6a9aad230f22325106e21adf06 to your computer and use it in GitHub Desktop.

Select an option

Save ricpumanes/12b82a6a9aad230f22325106e21adf06 to your computer and use it in GitHub Desktop.
Node crypto.pbkdf2 example to securely store and check passwords.

password.js

Tiny Node.js module to securely hash and compare passwords using pbkdf2 with per password random salt.

Usage

To hash a password:

var password = require('./password');

password.hash('p4ssw0rd').then(console.log); // hashed password

Later, to compare it:

var password = require('./password');

password.same('p4ssw0rd', hash).then(console.log); // true or false
var crypto = require('crypto');
var digest = 'sha256';
var iterations = 99999;
var keyLength = 32;
exports.hash = function(password) {
var executor = function(resolve, reject) {
var callback = function(error, salt) {
if (error) {
return reject(error);
}
var callback = function(error, key) {
if (error) {
return reject(error);
}
var buffer = new Buffer(keyLength * 2);
salt.copy(buffer);
key.copy(buffer, salt.length);
resolve(buffer.toString('base64'));
};
crypto.pbkdf2(password, salt, iterations, keyLength, digest, callback);
};
crypto.randomBytes(keyLength, callback);
};
return new Promise(executor);
};
exports.same = function(password, hash) {
var executor = function(resolve, reject) {
var buffer = new Buffer(hash, 'base64');
var salt = buffer.slice(0, keyLength);
var keyA = buffer.slice(keyLength, keyLength * 2);
var callback = function(error, keyB) {
if (error) {
return reject(error);
}
resolve(keyA.compare(keyB) == 0);
};
crypto.pbkdf2(password, salt, iterations, keyLength, digest, callback);
};
return new Promise(executor);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment