Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Created September 5, 2017 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iolloyd/6ddcfab1fff69cf00b9b640a82933444 to your computer and use it in GitHub Desktop.
Save iolloyd/6ddcfab1fff69cf00b9b640a82933444 to your computer and use it in GitHub Desktop.
method to create hash and salt
import crypto from 'crypto'
import semver from 'semver'
const processVersion = '0.12.0';
const pbkdf2DigestSupport = semver.gte(process.version, processVersion);
const pbkdf2 = (pwd, salt, options, callback) => {
const { iterations, keylen, digestAlgorithm } = options;
if (pbkdf2DigestSupport) {
crypto.pbkdf2(pwd, salt, iterations, keylen, digestAlgorithm, callback);
} else {
crypto.pbkdf2(pwd, salt, iterations, keylen, callback);
}
}
const createHashAndSalt = (pwd, options) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(options.saltlen, (randomBytesErr, buf) => {
if (randomBytesErr) {
return reject(randomBytesErr)
}
const salt = buf.toString(options.encoding);
pbkdf2(pwd, salt, options, (pbkdf2Err, hashRaw) => {
if (pbkdf2Err) {
return reject(pbkdf2Err)
}
return resolve({
hash: new Buffer(hashRaw, 'binary').toString(options.encoding),
salt
});
});
});
});
};
const options = {
'saltlen': 32,
'iterations': 25000,
'keylen': 512,
'encoding': 'hex',
'digestAlgorithm': 'sha256'
}
const wantedPassword = 'supersecret';
createHashAndSalt(wantedPassword, options).then(resp => {
console.log(resp)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment