Skip to content

Instantly share code, notes, and snippets.

@fmolliet
Created October 30, 2021 15:54
Show Gist options
  • Select an option

  • Save fmolliet/d0cfbaa92795aee686b721f5a007b677 to your computer and use it in GitHub Desktop.

Select an option

Save fmolliet/d0cfbaa92795aee686b721f5a007b677 to your computer and use it in GitHub Desktop.
Async function for hashPassword
const crypto = require('crypto');
async function hashPassword( password , configs = {} ) {
const config = {
hashBytes: configs.hashBytes || 64,
saltBytes: configs.saltBytes || 64,
iterations: configs.iterations || 872791
};
// Gera Salt
const salt = await new Promise(( resolve, reject) => {
crypto.randomBytes(config.saltBytes, function(err, salt) {
if (err) {
reject(err);
}
resolve(salt)
});
})
// Utiliza Password-Based Key Derivation function para gerar hash de senha cifrado
return await new Promise( (resolve, reject )=>{
crypto.pbkdf2(
password,
salt,
config.iterations,
config.hashBytes, "sha512",
(err, hash) => {
if (err) {
reject(err);
}
const buffer = new Buffer.alloc(hash.length + salt.length + 8);
buffer.writeUInt32BE(salt.length, 0, true);
buffer.writeUInt32BE(config.iterations, 4, true);
salt.copy(buffer, 8);
hash.copy(buffer, salt.length + 8);
resolve(buffer);
}
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment