使用MD5进行PHP摘要身份验证

时间:2011-11-03 09:13:54

标签: php http http-authentication digest

我写了一个类来使用HTTP身份验证以Digest方式验证用户身份。我读了几篇文章然后就搞定了。现在,我想让它使用Md5密码,但我似乎无法让它工作,这是验证用户的功能。

public function authenticate() {

// In case the user is not logged in already.
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {

    // Return the headers.
    $this->show_auth();

} else {

    // Parse the given Digest-data.
    $data = $this->parse_request($_SERVER['PHP_AUTH_DIGEST']);

    // Check the data.
    if (!$data) { 

        // Display an error message.
        die($this->unauthorized);

    } else {

        // Based on the given information, generate the valid response.
        $usr_password = "test";

        // Generate the response partly.
        $A1 = md5($data['username'].":".$this->get_realm().":".$usr_password);
        $A2 = md5($_SERVER['REQUEST_METHOD'].":".$data['uri']);

        // Generate the valid response.
        $val_response = md5($A1.":".$data['nonce'].":".$data['nc'].":".$data['cnonce'].":".$data['qop'].":".$A2);

        // Compare the valid response with the given response.
        if ($data['response'] != $val_response) {

            // Display the login again.
            $this->show_auth();

        } else {

            // Return true.
            return true;

        }

    }

}

}

所以想象一下$ usr_password =“test”将是$ usr_password = md5(“test”);

我如何比较密码?

感谢。

1 个答案:

答案 0 :(得分:0)

MD5 功能是哈希函数,是一种单向方法,可以为同一输入产生相同的结果。

因此,要比较$password1$password2而不透露(直接比较)它们两者,它应足以比较它们的哈希值:

$hash1 = md5($password1); // hash for pass 1
$hash2 = md5($password2); // hash for pass 2

if ($hash1 === $hash2) {
    // here goes the code to support case of passwords being identical
} else {
    // here goes the code to support case of passwords not being identical
}

足够清楚了吗?让我知道。