hash() 与 crypt() 函数比较 [英] hash() vs. crypt() function comparison

查看:23
本文介绍了hash() 与 crypt() 函数比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在实施登录系统.我想将密码和盐存储在数据库中.现在我发现有一个 hash() 和一个 crypt() 函数似乎做了同样的事情(对 SHA512 有效).

I'm currently implementing a login system. I want to store the password and the salt in a database. Now I found out that there is a hash() and a crypt() function which seems to do the same (valid for SHA512).

hash() 更新,似乎比 crypt() 支持更多的散列算法.或者我应该知道/关心其他任何差异吗?

hash() is newer and seems to support more hashing alogrithms than crypt(). Or there any other differences I should know/care about?

function generatePasswordHash($password){
    $salt = base64_encode(mcrypt_create_iv(8));
    $calculatedPasswordHash = crypt($password, '$1$' . $salt . '$');

    return $calculatedPasswordHash;
}

结果看起来像 $1$Qh6ByGJ9$zLn3yq62egvmc9D7SzA2u.

这里是我的密码检查功能:

Here my password checking function:

function checkLoginData($username, $password){
    global $db;

    $sql = "SELECT * FROM users WHERE username = :username";
    $result = $db->ExecuteQuery($sql, array("username"=>$username));

    if(!empty($result)){
        $result = $result[0];
        $savedPasswordHash = $result['password'];
        $splitted = explode("$", $savedPasswordHash);
        $salt = $splitted[2];
        $calculatedPasswordHash = crypt($password, '$1$' . $salt . '$');

        if($savedPasswordHash === $calculatedPasswordHash){
            return true;
        }
    }

    return false;
}

推荐答案

使用 hash 进行散列,例如在完整性检查中.直接使用指定的哈希算法.

Use hash for hashing, for example in integrity checks. It directly uses the specified hashing algorithm.

crypt 是一个特殊用途的函数.它用于密码散列和密钥派生.您需要传入一个盐,它间接确定了所使用的散列方案.即使您选择 CRYPT_SHA512,这也不是普通的 SHA512.这是一个使用 SHA512 作为构建块的密钥派生函数.特别是这种方案是故意缓慢的(隐藏暴力攻击)并且以安全的方式结合了盐和密码.

crypt is a special purpose function. It's used for password hashing and key derivation. You'll need to pass in a salt, which indirectly determines the hashing scheme used. Even if you choose CRYPT_SHA512 this isn't plain SHA512. It's a key derivation function that uses SHA512 as building block. In particular such a scheme is deliberately slow(hider brute-force attacks) and combines salt and password in a secure way.

对于日志系统中的密码散列,crypt 显然是正确的选择.

For password hashing in a log system, crypt is clearly the right choice.

这篇关于hash() 与 crypt() 函数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆