I have a problem. my hashed password values are not matching when retrieving salt value from database.
Register.php
- User enters username and password.
- Collect the username and password through POST.
- Generate a random salt value Add the salt value onto the end of the password value(entered by user). And hash the full value.
Insert username, salt,hashedpassword and original password into database (just for testing)
if (isset($_POST["usernameReg"]) && isset($_POST["passwordReg"])){ // filter everything but numbers and letters $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["usernameReg"]); $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["passwordReg"]); $salt = openssl_random_pseudo_bytes(1024); $hashedPassword = hash('sha256', $password.$salt); //$hashedPassword1 = hash('sha256', $password); $query = "INSERT INTO users (username, salt, hashedPassword, password) VALUES (:username, :salt, :hashedPassword, :password)"; $statement = $pdoConnection->prepare($query); $statement->bindValue(':username', $username, PDO::PARAM_STR); $statement->bindValue(':salt', $salt, PDO::PARAM_STR); $statement->bindValue(':hashedPassword', $hashedPassword, PDO::PARAM_STR); $statement->bindValue(':password', $password, PDO::PARAM_STR); $statement->execute();
}
login.php
- User enters username and password.
- Collect the username and password through POST.
- Check the username exists in the database.
- Get the salt value for that username from the database and add it to the end of the password entered by the user in the login form. Hash this value and store it into $_SESSION["newHashedValue”] variable.(for testing)
- Retrieve the original hashedValue from the database. Store it in $_SESSION[" dbHashedValue”] and compare values.
If the values match then we know the login password is correct. Problem: these values do not match and they should because im entering the same login details.
if (isset($_POST["username"]) && isset($_POST["password"])){ $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);
//check if this username and password exist in our database and are therefore valid $query = "SELECT * FROM users WHERE username=:username LIMIT 1"; $statement = $pdoConnection->prepare($query); $statement->bindValue(':username', $username, PDO::PARAM_STR); $statement->execute(); $statement->setFetchMode(PDO::FETCH_ASSOC); while($row = $statement->fetch()){ $saltPassword = $password.$row["salt"]; $newHashedValue = hash('sha256', $saltPassword); $dbHashedValue = $row["hashedPassword"]; //these two values are not matching but they should match $_SESSION["newHashedValue"] = $newHashedValue; $_SESSION["dbHashedValue"] = $dbHashedValue; }
}