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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题