Verifying Salted Passwords in Database Login
When developing a membership site, securing login credentials is crucial. One essential aspect is implementing salted passwords, which enhances password protection by adding a random string to the password before hashing it.
Problem:
In the provided code, the error in the login page allows any member to access the site despite incorrect password entries. This indicates an issue with the check for password validity.
Answer:
To verify a salted password, we cannot directly compare the entered password to the stored hash. Instead, we must:
Example Code for mysqli:
$mysqli = new mysqli($dbHost, $dbUser, $dbPassword, $dbName); // Find the stored password hash in the db $sql = 'SELECT password FROM users WHERE username = ?'; $stmt = $mysqli->prepare($sql); $stmt->bind_param('s', $_POST['username']); $stmt->execute(); // Check if user exists and fetch the hash $isPasswordCorrect = false; $stmt->bind_result($hashFromDb); if ($stmt->fetch() === true) { $isPasswordCorrect = password_verify($_POST['password'], $hashFromDb); }
Example Code for PDO:
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8"; $pdo = new PDO($dsn, $dbUser, $dbPassword); // Find the stored password hash in the db $sql = 'SELECT password FROM users WHERE username = ?'; $stmt = $pdo->prepare($sql); $stmt->bindValue(1, $_POST['username'], PDO::PARAM_STR); $stmt->execute(); // Check if user exists and fetch the hash $isPasswordCorrect = false; if (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) { $hashFromDb = $row['password']; $isPasswordCorrect = password_verify($_POST['password'], $hashFromDb); }
By following this process, you can effectively verify salted passwords in your login page, ensuring the security of your member site.
The above is the detailed content of How Do I Securely Verify Salted Passwords in a Database Login System?. For more information, please follow other related articles on the PHP Chinese website!