2016-03-18 43 views
-1

我正在使用PHP版本5.4我已经四处寻找了散列机制,但我无法让它工作。棘手的部分是用另一个用户尝试验证哈希密码,我在这里做错了什么?为什么不是这个哈希匹配发生?

//and yes I am using password as name in this example 

$password_entered ="cucumberball"; 
    $password_hash = crypt($password_entered); 

mysql_set_charset('utf8'); 
pdoConnect(); 

//insert hashed pass (same name and pass(hashed) for user) 
$stmt = $pdo->prepare("insert into user (name,password) values (:name,:password)"); 
    $stmt->bindParam(':name', $password_entered); 
    $stmt->bindParam(':password', $password_hash); 
    $stmt->execute(); 

    //retriving password from db and checking if its correct with the login password provided 
    $stmt = $pdo->prepare("select password from user where name = :name LIMIT 1;"); 
    $stmt->bindParam(':name', $password_entered); 
    $stmt->execute(); 

    $user = $stmt->fetch(PDO::FETCH_OBJ); 

    if(crypt($password_entered, $password_hash) == $user->password) { 
     // password is correct 
     echo "WORKS"; 
    }else{ 

     echo "did not work"; 
    } 
+0

注意:你正在保存数据库未加密的密码作为名称... – fusion3k

+0

我保存输入的密码作为名称。只为例 – Christopher

+1

[此示例](http://php.net/manual/en/function.crypt.php#114060)作品:从它开始(或使用它) – fusion3k

回答

1

当你比较你在加密密码和从数据库中的密码只有加密时腌制。

if(crypt($password_entered, $password_hash) == $user->password) {

此外,根据文档,你应该比较喜欢这个

你应该通过的crypt()作为盐的整个结果 比较密码,以避免出现问题时,使用不同的散列法 算法。 (如上面说,标准的基于DES密码 散列使用一个2字符的盐,但基于MD5的散列使用12)

if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) { 
    echo "Password verified!"; 
0

修复这个if语句:

if(hash_equals(crypt($password_entered, $password_hash), $password_hash)) 
{ 
    echo "WORKS"; 
} 

或者,因为在PHP 5.4没有hash_equals

if(crypt($password_entered, $password_hash) == $password_hash) 
{ 
    echo "WORKS"; 
} 

但是,如果没有hash_equals,你的散列vulne rable到timing attack

您也可以阅读this manual

+0

okey,精心制作。 – Christopher

+0

@Christopher为什么需要详细阐述一下“阅读[本手册](http://php.net/manual/en/function.crypt.php)”?“ – zaph

+0

没有看到链接 – Christopher