【发布时间】: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