問題描述
我想我已經使用函數 PASSWORD
直接從 mysql 數據庫中散列密碼(我在這里做錯了嗎?).我正在嘗試使用此代碼驗證該密碼:
I think i have hashed password using function PASSWORD
directly from mysql database(am i doing wrong here?). And i am trying to verify that password with this code:
if($submit)
{
$first=$_POST['first'];
$password=$_POST['password'];
$hash="*85955899FF0A8CDC2CC36745267ABA38EAD1D28"; //this is the hashed password i got by using function PASSWORD in database
$password=password_verify($password,$hash);
$db = new mysqli("localhost", "root","","learndb");
$sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
$result = $db->query($sql);
$result=mysqli_num_rows($result);
if($result>0)
{
session_start();
$_SESSION['logged_in'] = true;
session_regenerate_id(true);
header("Location:loginhome.php");
}
}
但是密碼不匹配.我在這里錯過了什么?
But the password is not matching. What am i missing here?
更新:
在所有的建議之后,我使用了 php 代碼中的 password_hash
來存儲到數據庫中.
After all the suggestions i have used password_hash
from php code to store into database.
$db = new mysqli("localhost", "root","","learndb");
$password=password_hash('ChRisJoRdAn123',PASSWORD_DEFAULT);
$sql="INSERT INTO admin (username,password)values('ChrisJordan','$password')";
$db->query($sql);
密碼仍然不匹配.
推薦答案
無法在數據庫中搜索加鹽密碼哈希.要計算散列,您需要使用 password_hash() 函數,因為您已經在插入語句中正確執行了.
One cannot search for a salted password hash in a database. To calculate the hash you need the password_hash() function as you already did correctly in your insert statement.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
要檢查密碼,您首先需要僅按用戶名搜索(使用準備好的查詢來避免 sql 注入):
To check a password, you first need to search by username only (used a prepared query to avoid sql injection):
$sql = 'select * from admin where username = ?';
$db->prepare($sql);
$db->bind_param('s', $first);
當你最終從數據庫中得到存儲的哈希值時,可以這樣檢查:
When you finally got the stored hash from the database, it can be checked like this:
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
這篇關于未使用函數 password_verify 驗證密碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!