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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办