2016-10-04 99 views
-2

註冊時,我正在加密密碼並將其存儲在數據庫中。登錄時,我再次加密密碼,並在數據檢索時嘗試與數據庫中的密碼匹配爲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...'); 
     } 
    }); 
}); 

離開有關語法,這是工作的罰款。但即使我輸入正確,註冊和登錄中的兩個passwrods都不匹配。

+3

您不應該加密用戶的密碼。你需要使用哈希,而不是一些強大的PBKDF2,bcrypt,scrypt和Argon2。由於散列函數是單向函數,因此您將無法「解密」散列。爲了驗證您的用戶,您可以再次通過散列函數運行密碼,以便與存儲在數據庫中的散列進行比較。查看更多:[如何安全地哈希密碼?](http://security.stackexchange.com/q/211/45523) –

+0

使用哈希也必須這樣做。我必須調用hash.digest兩次。如果我這樣做,會出現錯誤。如果我想這樣做,我還必須調用update,這會導致不同的加密字符串。請回答我的問題。不要置評。 @Artjom –

回答

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個字節。

相關問題