Last active
October 13, 2018 12:37
-
-
Save leejh3224/f442f019f3fc88abbc535e212e1a5acf to your computer and use it in GitHub Desktop.
This file contains 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 { pbkdf2, randomBytes } from 'crypto' | |
const iteration = 199999 | |
const hashLength = 64 | |
const digest = 'sha512' | |
// promisify native pbkdf2 function | |
const generateHash = (password: string, salt: string): Promise<string> => { | |
return new Promise((resolve, reject) => { | |
pbkdf2(password, salt, iteration, hashLength, digest, (err, key) => { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(key.toString('hex')) | |
} | |
}) | |
}) | |
} | |
// timingSafeEqual => https://nodejs.org/api/crypto.html#crypto_crypto_timingsafeequal_a_b | |
const validatePassword = async (password: string, origin: string, salt: string): boolean => { | |
try { | |
// if origin and hash shares 'password' and 'salt', it would match | |
const hash = await generateHash(password, salt) | |
return timingSafeEqual(Buffer.from(origin), Buffer.from(hash)) | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
const generatePassword = async (password): Promise<string> => { | |
// crypto provides utility function to generate randomBytes | |
const salt = await randomBytes(16).toString('hex') | |
try { | |
await generateHash(password, salt) | |
} catch (error) { | |
console.log(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment