我有问题。从数据库中检索salt值时,我的哈希密码值不匹配。
Register.php
将用户名,salt,哈希密码和原始密码插入 数据库(仅用于测试)
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
如果值匹配,那么我们知道登录密码是正确的。 问题:这些值不匹配,因为我输入相同的登录详细信息。
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 ["密码"]);
//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;
}
}
答案 0 :(得分:2)
$salt = openssl_random_pseudo_bytes(1024); //will generate 2048 chars since a character is half a byte.
将生成一个2048个字符的字符串。因此,解决方案是将salt
列的大小增加到2048,这有点过分,或者生成32个字节,这将是64个字符。
$salt = openssl_random_pseudo_bytes(32); //will generate 64 chars
有关此功能的更多信息http://php.net/manual/en/function.openssl-random-pseudo-bytes.php
sha256散列的长度为64,因此hashedPassword
列的长度应为64.(顾名思义,256位= 32bytes = 64个字符)