Skip to content

Instantly share code, notes, and snippets.

@gibatronic
Last active May 5, 2023 12:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gibatronic/141ab0ee0507cd2c8bd84e12fe9c2097 to your computer and use it in GitHub Desktop.
Save gibatronic/141ab0ee0507cd2c8bd84e12fe9c2097 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);
};
@prodigga
Copy link

prodigga commented Jul 3, 2020

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment