When building secure applications, handling salted passwords is crucial. However, it can be challenging to verify user passwords against stored salted hashes effectively. This article will guide you through the steps involved in retrieving a salted password from a database and authenticating the user.
Retrieving the Salted Password:
The example code below demonstrates how to retrieve the salted password hash from a MySQL database using an mysqli connection:
<?php $servername = 'localhost'; $username = 'root'; $pwd = ''; $dbname = 'lp001'; $connect = new mysqli($servername,$username,$pwd,$dbname); if ($connect->connect_error){ die('connection failed, reason: '.$connect->connect_error); } $name = mysqli_real_escape_string($connect, $_POST['name']); $saltQuery = "SELECT salt FROM users WHERE name = '$name';"; $result = mysqli_query($connect, $saltQuery); if ($result === false){ die(mysqli_error()); } $row = mysqli_fetch_assoc($result); $salt = $row['salt']; ?>
This code connects to the database, sanitizes the user input, and retrieves the salt associated with the given username from the users table. The salt is essential for verifying the password.
Verifying the User Password:
Once the salted password hash is retrieved, you can verify if the user-provided password matches it. The following code shows how to do this using the password_hash() and password_verify() functions:
<?php $password = mysqli_real_escape_string($connect, $_POST['password']); $saltedPW = $password.$salt; $hashedPW = hash('sha256', $saltedPW); $sqlQuery = "SELECT * FROM users WHERE name = '$name' AND password = '$hashedPW'"; if (mysqli_query($connect, $sqlQuery)){ echo '<h1>Welcome to the member site '.$name.'</h1>'; }else{ echo 'error adding the query: '.$sql_q.'<br> Reason: '.mysqli_error($connect); } ?>
Here, the provided password is salted using the retrieved salt, then hashed using a secure hash function. The hashed password is then compared to the stored hashed password in the database. If the passwords match, the user is authenticated.
By following these steps, you can effectively retrieve a salted password from a database and verify the user's password without exposing the actual password. This approach ensures the security of user credentials while providing efficient and secure authentication.
The above is the detailed content of How to Verify a User Password Against a Salted Hash in a Database?. For more information, please follow other related articles on the PHP Chinese website!