Charan Cherry Charan Cherry - 1 year ago 52
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.
in registration and
in login are not matching.

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

Login'/login', function(req, res){

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

var query = conn.query("SELECT * FROM users WHERE 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 +'utf8');
pswrd = pswrd.substring(1, pswrd.length-2);
if(!err && req.body.pwd == pswrd){
} 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 Source

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 +='hex');
    return encrypted;   
}"/register", function(req, res){
    var pswd = encryptText(req.body.pwd);
})"/login", function(req, res){
    var pswd = encryptText(req.body.pwd);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download