snowshoes
6/20/2019 - 12:45 PM

Using bcrypt with promises to hash a password and then verify it

Using bcrypt with promises to hash a password and then verify it

let bcrypt = require('bcrypt-nodejs');

let password = "hello";
let stored_hash = "";

// first generate a random salt
function genSalt(password) {
    return new Promise((resolve,reject) => {
        bcrypt.genSalt(10,function(err,salt) {
            if (err) {
                reject(err);
            }
            else {
                resolve({
                    salt:salt,
                    password:password
                });
            }
        });
    });
}

// hash the password with the salt
function genHash(salt,password) {
    return new Promise((resolve,reject) => {
        bcrypt.hash(password,salt,null,function(err,hash) {
            if (err) {
                reject(err);
            }
            else {
                resolve({
                    salt:salt,
                    password:password,
                    hash:hash
                });
            }
        });
    });
}

// execute in sequence
console.log("store");
genSalt(password)
.then(function(result) {
    return genHash(result.salt,result.password);
    })
.then(function(result) {
    console.log('store hash in user profile :', result);
    stored_hash = result.hash;
})
.catch(function(err) {
    console.log(err);
});

// =====================================================
function lookupUser(user,passwd) {
    return new Promise((resolve,reject) => {
        // lookup the user in the stored database
        // in this case its not async so just resolve with the stored hash
        resolve({
            user:user,
            password:passwd,
            hash1:stored_hash
        })
    })
}

function reHash(user,password,hash1) {
    let salt  = hash1.substr(0,30);
    return new Promise((resolve,reject) => {
        bcrypt.hash(password,salt,null,function(err,hash2) {
            if (err) {
                reject(err);
            }
            else {
                resolve({
                    user:user,
                    salt:salt,
                    password:password,
                    hash1:hash1, // stored hash
                    hash2:hash2  // generated hash
                });
            }
        });
    });
}

// lookup and verify
setTimeout(function() {
    console.log("verify");
    lookupUser("joe",password) 
    .then(function(result) {
        return reHash(result.user,result.password,result.hash1);
    })
    .then(function(result) {
        console.log(result.hash1);
        console.log(result.hash2);
        if (result.hash1 === result.hash2) {
            console.log('verified');
        }
        else {
            console.log('failed');
        }
    })
    .catch(function(err) {
        console.log(err);
    });
},1000);