1

我有两个功能,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 字符散列(我的意思是它们是完全不同的散列)。

4

2 回答 2

2

如果你所有的substr都是正确的,你只是忘了附加";" . $DynamicSalt$TestHash

顺便提一句。这违反了第一条数据库规范化规则:“值必须是原子的”。盐应存放在单独的字段中。

于 2012-04-20T22:05:19.720 回答
1

这可能与您如何拆分要测试的哈希有关。例如,您正在尝试获取长度为 151 个字符的盐。

试试这个:

function ValidatePassword($password, $dbHashedPassword) {
    list($CorrectHash, $DynamicSalt) = explode(";",$dbHashedPassword,2);
    return $CorrectHash == hash("sha512",$password.$DynamicSalt);
}
于 2012-04-20T22:03:44.997 回答