比较 PHP 中的两个 md5 加密密钥



为什么在比较两个相等的 md5 键后显示incorrent password

<?php
if (isset($_POST['user_password']) && !empty($_POST['user_password'])) {
$user_password = $_POST['user_password'];
echo $user_passkey = md5($user_password).'<br>';
$filename = 'hash.txt';
$handle = fopen($filename, 'r');
echo $file_password  = fread($handle, filesize($filename));
if ($user_passkey==$file_password) {
echo 'correct password';
} else {
echo 'Incorrect Password';
}
} else {
echo 'Please enter a password';
}
?>
<form action="index.php" method="POST">
Password:
<input type="text" name="user_password"><br><br>
<input type="submit" value="Submit">
</form>

另一个 md5 创建的文件是:

<?php 
$string = 'password';
$string_hash = md5($string);
echo $string_hash;
?>

加密的密钥保存在另一个名为 hash.txt 的文件中,位于同一文件夹中。 echo$user_passkey和 echo$file_password都显示确切的哈希密钥(为用户输入和以前加密的密钥文件哈希.txt给出相同的"密码"(,但没有在 if 语句中进行比较。

为什么它不能按预期工作?

它不起作用,因为您从用户输入生成的 md5 哈希恰好在最后有一个来自调试输出的<br>

1( 更改

md5($user_password).'<br>';

md5($user_password);

2( 改变

if ($user_passkey==$file_password)

if ($user_passkey==trim($file_password))

它会告诉你,哈希是相同的,因为它确实是相同的哈希,但第一个在末尾有换行符,这使得它与另一个不同的字符串。

这就是我要做的

<?php
$filename = 'hash.txt';
$handle = fopen($filename, 'r');
echo $file_password  = fread($handle, filesize($filename));
$name=md5('bimbo');
if($name==$file_password){
	echo "string";
}
?>

<?php
if (isset($_POST['user_password']) && !empty($_POST['user_password'])) {
$user_password = $_POST['user_password'];
$user_passkey = md5($user_password);
$new_userpass=$user_userpass."<br/>";
$filename = 'hash.txt';
$handle = fopen($filename, 'r');
echo $file_password  = fread($handle, filesize($filename));
if ($user_passkey==$file_password) {
echo 'correct password';
} else {
echo 'Incorrect Password';
}
} else {
echo 'Please enter a password';
}
?>
<form action="index.php" method="POST">
Password:
<input type="text" name="user_password"><br><br>
<input type="submit" value="Submit">
</form>

一个 md5(( 示例

<?php
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Would you like a green or red apple?";
}
?>

最新更新