-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都不匹配。
您不應該加密用戶的密碼。你需要使用哈希,而不是一些強大的PBKDF2,bcrypt,scrypt和Argon2。由於散列函數是單向函數,因此您將無法「解密」散列。爲了驗證您的用戶,您可以再次通過散列函數運行密碼,以便與存儲在數據庫中的散列進行比較。查看更多:[如何安全地哈希密碼?](http://security.stackexchange.com/q/211/45523) –
使用哈希也必須這樣做。我必須調用hash.digest兩次。如果我這樣做,會出現錯誤。如果我想這樣做,我還必須調用update,這會導致不同的加密字符串。請回答我的問題。不要置評。 @Artjom –