密码将相同的字符串加密到不同的字符串?

时间:2016-10-04 05:10:13

标签: node.js encryption

注册时我正在加密密码并将其存储在DB中。登录时,我再次加密密码,并尝试在数据检索时将数据库中的密码与SELECT * FROM table where uname=Username AND pwd=encryptedPasswd匹配。但即使我输入密码,密码也不匹配。怎么解决这个?以下是我的代码。注册时pswd和登录中的pswds不匹配。

注册

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...');
            }
        });
    }
});

登录

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...');
        }
    });
});

离开语法,它工作正常。但即使我输入正确,注册和登录中的密码都不匹配。

1 个答案:

答案 0 :(得分:0)

最后我得到了我的问题的答案。当有人面对上述情况时,他只需要在一个函数中包含加密部分,然后他必须从不同的后调用中调用该函数。我将算法从aes192更改为aes-256-gcm。 这是我的代码:

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);
})

现在密码在两种情况下都匹配。密码必须是32字节,iv必须是16字节

相关问题