Search code examples
javascriptnode.jscryptojs

How can I compare encrypted password strings correctly?


I have a basic html page with a username and password input boxes. Along with a login button. I am using cryptojs to try and compare encryption strings.

I believe my problem is because I'm randomly generating my key and iv. Do y'all have any suggestions on what I could change?

app.post('/authenticate',function(req,res){
conn.open(connString, function(err){
if(err) return console.log(err);

var loginID = req.body.LoginID,
    passWord = req.body.PassWord;

//-------------------------Security---------------------------
    // create random Word Arrays for key and Salt
    var key = CryptoJS.lib.WordArray.random(16);
    var iv  = CryptoJS.lib.WordArray.random(16);

    // Encrypt Password using key and Salt. Changes every time but will always decrypt to same password.
    var encrypted = CryptoJS.AES.encrypt(passWord, key, { iv: iv }).toString();
    var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv }).toString();

    console.log(decrypted);

//-------------------------END Security------------------------    

conn.query("SELECT PassWord from pub.User WHERE LoginID ='" + loginID  + "'",function(err,data){

    if(err) return console.log(err);   
    res.json(data);

    setValue(data);

    function setValue(value) {
    someVar = value;
    }
        for(key in someVar) {
            if(someVar.hasOwnProperty(key)) {
                var value = someVar[key];
                console.log(value.PassWord);
                console.log(encrypted);

                    if(value.PassWord == encrypted)
                    {
                        console.log("pass");
                    }
                    else
                    {
                        console.log("Fail");
                    }
            }
        }

        conn.close(function(){
        console.log('Login Complete');
        }); 
    }); // conn.query

}); //END conn.open(connString, function(err){
}); // END app.post('/authenticate'

Thank You,


Solution

  • Why did you choose Cryptojs?, I think there are better alternatives, like Bcrypt (that is what I commonly use), they expose a function to compare the string directly with the hash value, and that's it.

    Give it a try: https://www.npmjs.com/package/bcrypt