在登录时从数据库中调用带有salt的blowfish加密

时间:2018-03-21 10:57:35

标签: php mysql password-encryption

我很快就会对这个问题进行说明。我相信这个等式的一面已经找到了,但是一旦哈希在数据库中,就无法弄清楚如何登录。我在注册时加密密码有以下内容:

    $blowfish_hash = "$2y$10$";
    $salt_length = 22;

    $salt = Generate_Salt($salt_length);
    $hash_combined = $blowfish_hash . $salt;

    $hash = crypt($password, $hash_combined);

    $password = $hash;

Generate_Salt()功能如下:

function Generate_Salt($length) {

  $unique_rndm_str = md5(uniqid(mt_rand(), true));
  $base64_string = base64_encode($unique_rndm_str);

  $mod_Base64_str = str_replace('+', '.', $base64_string); 
  $salt = substr($mod_Base64_str, 0, $length);

    return $salt;
}

一旦我注册,我就会得到这个漂亮的长哈希 - 太棒了!但是,当我去登录时,我不确定如何调用哈希来检查给定的密码:$_POST['log_password'];

使用md5非常简单,我只是以这种方式加密$password = md5($password);并以这种方式调用$password = md5($_POST['log_password']);但是读起来我意识到这不是一种安全的方法。

我已经在这几个小时了,有人可以为我解释这个吗?任何帮助,将不胜感激。

ep

1 个答案:

答案 0 :(得分:1)

这比你想象的容易得多。只需使用函数password_hash(),它将调用crypt()函数并处理安全盐的生成。

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);
相关问题