Charan Cherry Charan Cherry - 2 months ago 6
Node.js Question

Cipher encrypting the same string to different string?

On registration I am encrypting the password and storing it in DB. On login, I am again encrypting the password and trying to match with the password in DB at the time of data retrieval as

SELECT * FROM table where uname=Username AND pwd=encryptedPasswd
. But the passwords are not matching even I entered same. How to resolve this? Below is my code.
pswd
in registration and
pswds
in login are not matching.

Registration

app.post("/register", function(req, res){
// Assume I have a value in post.pwd
var pswd = cipher.update(post.pwd, 'utf8', 'hex');
pswd = "'" + pswd + cipher.final('hex') + "',";
console.log(pswd);
// Assume I have variable with value
conn.query("INSERT INTO users VALUES (name, pswd)", function(err, rows, fields){
if(!err){
res.send(User);
} else{
console.log('Error while parsing the query...');
}
});
}
});


Login

app.post('/login', function(req, res){


var pswds = cipher.update(req.body.pwd, 'utf8', 'hex');
pswds = "'" + pswds + cipher.final('hex') + "',";
pswds = "'" + pswds + "',";
console.log(pswds);

var query = conn.query("SELECT * FROM users WHERE phone='" + req.body.phone +
"AND pwd='" + pswds + "'", function(err, rows, fields){
const decipher = crypto.createDecipher('aes192', 'encryptedpwd');
var pswrd = decipher.update(rows[0].pwd, 'hex', 'utf8');
pswrd = pswrd + decipher.final('utf8');
pswrd = pswrd.substring(1, pswrd.length-2);
if(!err && req.body.pwd == pswrd){
res.send(rows[0]);
} else{
console.log('Error while parsing the query...');
}
});
});


Leave about the syntax, it is working fine. But both passwrods in registration and login are not matching even I entered correctly.

Answer

Finally I got the answer to my question. When someone face the above situation he just need to wrap up the encryption part in a function and then he has to call that function from different post calls. I changed the algorithm from aes192 to aes-256-gcm. Here is my code:

var crypto = require('crypto'),
    algorithm = 'aes-256-gcm',
    password = '3zTvzr3p67VC61jmV54rIYu1545x4TlY', // must be 32-bytes
    // do not use a global iv for production, 
    // generate a new one for each encryption
    iv = '60iP0h6vJoEa'; // must be 16-bytes

var encryptText = function(text){
    var cipher = crypto.createCipheriv(algorithm, password, iv)
    var encrypted = cipher.update(text, 'utf8', 'hex')
    encrypted += cipher.final('hex');
    return encrypted;   
}
app.post("/register", function(req, res){
    var pswd = encryptText(req.body.pwd);
    console.log(pswd);
})
app.post("/login", function(req, res){
    var pswd = encryptText(req.body.pwd);
    console.log(pswd);
})

Now the passwords are matching in both cases. And the password must by 32-bytes and iv must be 16-bytes