Created
September 5, 2017 13:37
-
-
Save iolloyd/6ddcfab1fff69cf00b9b640a82933444 to your computer and use it in GitHub Desktop.
method to create hash and salt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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