我遇到問題。當我從數據庫中檢索SALT-Value時,我的哈希密碼與我數據庫中的密碼不相等。在SQL數據庫中生成的鹽在從那裏檢索時不等於
register.php
- 生成隨機鹽,將其添加到所述密碼的末尾。
- 哈希值。
- 在數據庫中插入用戶名,散列密碼和salt。
while($row){
$SALT = random_bytes(32);
$SALT = bin2hex($SALT);
$query = "SELECT 1 FROM usr_accounts WHERE SALT = :SALT";
$query_params = array(':SALT' => $SALT);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if(empty($row)){
break;
}
}
for($hashnr = 0; $hashnr < 128; $hashnr++){
$PASSWORD = hash('sha256', $_POST['PASSWORD'].$SALT);
}
$query = "INSERT INTO usr_accounts (USERNAME, PASSWORD, SALT, EMAIL) VALUES (:USERNAME, :PASSWORD, :SALT, :EMAIL)";
$query_params = array(':USERNAME' => $_POST['USERNAME'], ':PASSWORD' => $PASSWORD, ':SALT' => $SALT, ':EMAIL' => $_POST['EMAIL']);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
的login.php
- 檢索來自數據庫中的數據(鹽),將其添加到所述密碼的末尾。
- 哈希值。
- 檢查密碼值是否相等。
$query = "SELECT ID, USERNAME, PASSWORD, SALT FROM usr_accounts WHERE USERNAME = :USERNAME";
$query_params = array(':USERNAME' => $_POST['USERNAME']);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row){
for($hashnr = 0; $hashnr < 128; $hashnr++){
$check_password = hash('sha256', $_POST['PASSWORD'].$row['SALT']);
}
}
只需使用內置的PHP密碼庫。更安全,更容易 – JimL