为什么我的PHP密码哈希比较不起作用?

时间:2012-04-20 21:59:49

标签: php hash passwords sha512

我有两个功能,HashPassword()ValidatePassword

第一个用动态盐哈希注册表格上给出的密码,第二个验证密码。

基本上,我正在检查密码哈希值是否与之匹配。在我的登录表单上,当我调用ValidatePassword()函数时,我已经测试了ValidatePassword()中的哈希值,以确保我在写入位置拆分哈希值进行比较,但我在比较它们时,回声出一个不同的哈希。

可能更容易看两个功能来更好地解释。

<?php

// hashes a users password along with a dynamic salt
// dynamic salt is stored with users password and is seperated by a ;
function HashPassword($password){
    // creates a dynamic salt
    $DynamicSalt       = uniqid('', true);
    // hash the password given from user along with dynamic salt
    $HashedPassword    = hash('sha512', $password . $DynamicSalt);
    // combine the hashed password seperated by ; then the dynamic salt to store in database
    $final             = $HashedPassword.';'.$DynamicSalt; // this value is stored in database like: c29fc9e4acdd2962c4db3f108bee728cf015c8f6388ab2cd4f21e405f9d2f13b2d53a1ab8629aa21c3453906a98aff0d4b9a0e14bfc2c553a4f9c7c0c32fc58a;4f91cfc746b426.53641182
    return $final;
}

// validate password user entered ($password = password from user | $dbHashedPassword = hash from database)
function ValidatePassword($password, $dbHashedPassword){
    // we need to get the password hash before the salt, (fetch just the first 128 characters from database hash)
    $CorrectHash = substr($dbHashedPassword, 0, 128);
    // get the dynamic salt from end of sha512 hash (
    $DynamicSalt = substr($dbHashedPassword, 129, 151); // get just the dynamic salt part of the db hash
    // hash the password from user and the dynamic salt which we got from the end of the hash from database
    $TestHash    = hash('sha512', $password . $DynamicSalt);

    return ($CorrectHash == $TestHash);


    // WHEN I ECHO OUT THE THREE VARIABLES $CorrectHash, $DynamicSalt and $TestHash
    // THE $CorrectHash (from db, first 128 chars) is not the same as $TestHash
    // AND TO MAKE SURE I AM SPLITTING THE HASH AND DYNAMIC SALT InN THE CORRECT PLACE I ECHO OUT
    // $DynamicSalt and it is split in the correct place showing the 23 characters which the dynamic salt is 23 characters
    // BUT WHEN I COMBINE THE $password and $DynamicSalt in $TestHash it shows a completely different hash from the $CorrectHash (which we got and split from database)
}

?>

我不确定是什么问题,但似乎我在正确的位置拆分哈希和动态盐,因为当我回显它显示前128个字符(sha512)然后是动态盐(23个字符)但是当回显出两个128个字符的哈希时,它们不匹配(我的意思是它们是完全不同的哈希)。

2 个答案:

答案 0 :(得分:2)

如果您的所有substr都是正确的,则只是忘了将";" . $DynamicSalt添加到$TestHash

顺便说一句。这违反了第一个数据库规范化规则:“值必须是原子的”。盐应该存放在一个单独的领域。

答案 1 :(得分:1)

这可能与你如何分割你正在测试的哈希有关。例如,你试图得到一个长151个字符的盐。

试试这个:

function ValidatePassword($password, $dbHashedPassword) {
    list($CorrectHash, $DynamicSalt) = explode(";",$dbHashedPassword,2);
    return $CorrectHash == hash("sha512",$password.$DynamicSalt);
}