gpt4 book ai didi

php - 比较PHP中密码的哈希值

转载 作者:行者123 更新时间:2023-11-29 05:24:28 24 4
gpt4 key购买 nike

作为学习 php 的一部分,我想尝试注册和登录页面,但是,site我正在关注如何使用 MySQLI 存储密码,但我没有使用它:

散列密码

$password1 = 'hello123';
// A higher "cost" is more secure but consumes more processing power
$cost = 10;

// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');

// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;

// Value:
// $2a$10$eImiTXuWVxfM37uY4JANjQ==

// Hash the password with the salt
$hash = crypt($password1, $salt);

我一直在找回密码,但是,这是该网站的代码:

$username = 'Admin';
$password = 'gf45_gdf#4hg';

$sth = $dbh->prepare('
SELECT
hash
FROM users
WHERE
username = :username
LIMIT 1
');

$sth->bindParam(':username', $username);

$sth->execute();

$user = $sth->fetch(PDO::FETCH_OBJ);

// Hashing the password with its hash as the salt returns the same hash
if ( crypt($password, $user->hash) === $user->hash ) {
// Ok!
}

据我所知,他获取了数据库中用户密码的哈希值,并将使用哈希传递的密码与数据库中的密码进行比较和检查。

我一直在尝试这个,但结果哈希与原始哈希永远不一样:

$pwdtocheck = 'hello123';

// no call do DB yet, doing this on the same page after hashing, the $hash is the same as above
$pwdhash = crypt($pwdtocheck, $hash);

// if I echo $pwdhash it's never exactly the same as the $hash.
if ( $pwdhash === $hash) {
echo "same pwd";
}

最佳答案

我在您的代码中看不到实际问题,也许您的数据库字段小于 60 个字符,或者您正在比较不同的密码。在每种情况下,都有一种更简单、更安全的哈希密码方法,只需使用新函数 password_hash()password_verify() .还有一个 compatibility pack对于早期的 PHP 版本。

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

关于php - 比较PHP中密码的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com