【问题标题】:Does this code use Bcrypt or just plain blowfish?这段代码是使用 Bcrypt 还是只是简单的河豚?
【发布时间】:2012-05-17 08:58:47
【问题描述】:

我正在在线学习 php 安全性(使用 php 5.4),并遇到了以下我想了解/使用的代码。以下代码是否使用 bcrypt,它是河豚的良好实现吗? 如果存在问题,您能否建议修复或资源。谢谢。

    class PassHash {  

    // blowfish  
    private static $algo = '$2a';  

    // cost parameter  
    private static $cost = '$10';  

    // mainly for internal use  
    public static function unique_salt() {  
        return substr(sha1(mt_rand()),0,22);  
    }  

    // this will be used to generate a hash  
    public static function hash($password) {  

        return crypt($password,  
                    self::$algo .  
                    self::$cost .  
                    '$' . self::unique_salt());  

    }  

    // this will be used to compare a password against a hash  
    public static function check_password($hash, $password) {  

        $full_salt = substr($hash, 0, 29);  

        $new_hash = crypt($password, $full_salt);  

        return ($hash == $new_hash);  

    }  

}  

以下是用户注册时的用法:

// include the class 
require ("PassHash.php");
// ...
// read all form input from $_POST
// ...
// do your regular form validation stuff
// ...
// hash the password
$pass_hash = PassHash::hash($_POST['password']);
// store all user info in the DB, excluding $_POST['password']
// store $pass_hash instead
// ...

这是用户登录过程中的用法:

// include the class  
require ("PassHash.php");        
// read all form input from $_POST
// ...
// fetch the user record based on $_POST['username']  or similar  
// ...
// ... 
// check the password the user tried to login with  
if (PassHash::check_password($user['pass_hash'], $_POST['password']) {  
    // grant access  
    // ...  
} else {  
    // deny access  
    // ...  
}  

【问题讨论】:

  • 另外:我需要将 salt 存储在 mysql 中还是将其保留为 passhash 类的内部函数?
  • 你不需要存储盐,它已经在 PassHash::hash 的返回值中。是的,这是一种类似于 bcrypt 的技术。与仅使用核心 PHP 所能获得的一样好。
  • 那么唯一盐包含在哈希中?这不就像把钥匙交给黑客吗?或者盐的部分也被加密了……盐和哈希不应该分开吗?
  • 我也讨厌学究气,但它是相似的还是相同的?我是否应该以某种方式增加轮数(如果是这种情况,则需要代码示例)。
  • 我不知道它们是否相同,您必须查看 crypt() 源代码。它们都是基于河豚的。此外,salt 与密钥完全不同,它只是保护您免受基于彩虹表的攻击。

标签: php hash passwords blowfish bcrypt


【解决方案1】:

简答:

是的,它确实使用 bcrypt 河豚(在 PHP 中河豚是 bcrypt 的当前算法)

正确答案:

为什么不使用受信任的 PHP 兼容性库,例如 this one?

与您发布的相比,使用它的好处是什么? :

  1. 被很多人广泛使用(必须被社区信任和接受)

  2. 允许与 php 5.5 本机 bcrypt 函数(因此命名为 passwd_compat)向前兼容更多信息:Info Here!

  3. 允许进行天才的重新哈希(几乎如果您决定提高算法的成本,您可以轻松地这样做并检查成本是否与库文件中的成本匹配,如果不匹配,那么您可以更新密码)

底线:如果您不知道自己在做什么,那么您只能使用 bcrypt 出错。要记住的一件事是:如果已经有轮子,就不要重新发明轮子。

希望这个答案可以帮助您/扩展您的知识。

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 2014-09-05
    • 2022-10-08
    • 1970-01-01
    • 2017-07-24
    • 2023-03-29
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多