dsklzerpx64815631 2015-02-08 23:45 采纳率: 100%
浏览 42

如何比较用户输入的散列密码?

I want my login password to be secured. So I came up to use the PHP's crypt() function to hash the password before inserting it to database. But Im having trouble when comparing the user input password from the converted hash password. Here's my code:

<?php
$password = 'hello_password';

# A higher "cost" is more secure
$cost = 10;

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

# Blowfish algorithm. 
$salt = sprintf("$2a$%02d$", $cost) . $salt;
$salted_password = $password . $salt;  // apply salt to password

# hash the password
$hash_password = hash('sha256', $salted_password);

$userInput = 'hello_password';  // suppose this is the user input password 

if (hash('sha256',$userInput) == $password) {
    echo "Password Verified.";
}
else {
    echo "Incorrect Password";
}

?>

But it always displays Incorrect Password although my password is correct. I don't want to use "hash_equals" function as it is not supported with my current PHP version. Can someone help me with this ? Thanks

  • 写回答

1条回答

  • dquoj04882 2015-02-09 00:15
    关注

    You're comparing a hashed user input to the actual user password. So of course this is never going to work.

    You're basically asking if hash == 'hello_password'. A hash will never match that, that is the whole point of a hash. You also aren't using the salt with the user input.

    You hash the actual password with a salt which is fine:

    $salted_password = $password . $salt;  // apply salt to password
    
    # hash the password
    $hash_password = hash('sha256', $salted_password);
    

    So you need to hash the user input with the salt, the same way:

    $salted_input = $userInput . $salt;  // apply salt to user input
    
    # hash the input
    $hash_input = hash('sha256', $salted_input);
    

    Then you can compare $hash_input with $hash_password.

    You also aren't using a salt properly. The salt is supposed to be used in the storage of the password to prevent rainbow table attacks. Randomly generating a salt to apply to both the input and the password at the time of comparison is pointless.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)