首页 文章

bcrypt salt获取密码和费用

提问于
浏览
0

我刚刚读到了关于bcrypt以及它到底有多好 . 据我所知,我使用盐和其他方法,如MD5,SHA1,SHA2等,以防止彩虹攻击 . bcrypt需要一个盐来告诉它成本 .

我提出的问题很少:

  • 我是否需要在数据库中为每个密码存储一个盐?或者我可以为每个密码使用相同的盐?

  • 费用如何运作?成本15和成本20之间有什么不同?我知道它与迭代有关,但每次迭代究竟做了什么?

1 回答

  • 3

    PHP的文档对表达式"salt"有点误导,实际上 crypt() 函数需要哈希参数,而salt只是这个参数的一部分 .

    好处是,所有参数都将包含在生成的60个字符的哈希字符串中,因此您不需要单独存储它们,只需存储字符串即可 . 成本因子提高到2的幂,这意味着,将成本因子增加1,将使计算时间加倍 .

    PHP现在有一个函数password_hash(),可以为您处理所有困难的部分 . 使用此函数而不是crypt,它将生成一个安全的随机盐 .

    // Hash a new password for storing in the database.
    // The function automatically generates a cryptographically safe salt.
    $hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
    
    // 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($password, $existingHashFromDb);
    

    我写了一个关于这个主题的教程,如果你有兴趣看看here .

相关问题