Home >Backend Development >PHP Tutorial >Why Does My Member Site Bypass Password Checks Even When Salted Passwords Are Used?
How to Distinguish Between Salted and Plain Passwords in Database Authentication
In database authentication, safeguarding passwords is crucial. One prevalent technique involves using salted passwords, where a random string (salt) is appended to the password before hashing. This enhances security by making it exponentially harder to crack passwords.
The Challenge: Verifying Member Logins
When implementing a member site with salted passwords stored in MySQL, a common error occurs during the login authentication process. Login attempts seem to bypass password checks incorrectly, allowing unauthorized access to the site.
Inspecting the Problem Code
The following code snippet is used to validate member logins:
$name = mysqli_real_escape_string($connect, $_POST['name']); $password = mysqli_real_escape_string($connect, $_POST['password']); $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']; $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); }
The Solution: Proper Password Verification
The issue arises from using a direct password comparison in the SQL query. Since the stored passwords are salted, this method misinterprets all login attempts as valid. To rectify this, we need to implement the following steps:
Example Code Using mysqli:
// Connect to the database $mysqli = new mysqli($servername, $username, $password, $dbname); // Initialize variables $username = mysqli_real_escape_string($mysqli, $_POST['username']); $password = mysqli_real_escape_string($mysqli, $_POST['password']); // Fetch the salted hash for the specified username $query = "SELECT password FROM users WHERE username = ?"; $stmt = $mysqli->prepare($query); $stmt->bind_param('s', $username); $stmt->execute(); $stmt->bind_result($hashedPassword); $stmt->fetch(); // Verify the entered password if (password_verify($password, $hashedPassword)) { // Login successful echo '<h1>Welcome to the member site '.$username.'</h1>'; } else { // Password did not match echo 'Invalid login credentials'; }
The above is the detailed content of Why Does My Member Site Bypass Password Checks Even When Salted Passwords Are Used?. For more information, please follow other related articles on the PHP Chinese website!