如何让symfony2安全BCRYPT编码器与php crypt()函数一起使用

时间:2013-06-23 22:37:12

标签: php authentication symfony passwords bcrypt

我正在使用bcrypt来哈希我的密码,似乎symfony2身份验证系统的生产与php的本机crypt功能相同。贝娄是我为我的用户密码生成的盐:

 $salt = '$2y$13$' . substr(md5(uniqid(rand(), true)),0,21) . '$';
 $this->setPassword('test',$salt);

在我的security.yml文件中,我只是在做:

encoders:
    Blogger\BlogBundle\Entity\User:
        algorithm:  bcrypt
        iterations: 13

为什么两种编码方法会生成不同的哈希值?我使用的库是ircmaxell / password-compat。

2 个答案:

答案 0 :(得分:3)

在Symfony2中使用它的最佳方法是使用get the encoder。

use \Blogger\BlogBundle\Entity\User;

$user = new User();

$encoderFactory = $this->get('security.encoder_factory');
$encoder = $encoderFactory->getEncoder($user);

$salt = 'salt'; // this should be different for every user
$password = $encoder->encodePassword('password', $salt);

$user->setSalt($salt);
$user->setPassword($password);

如果您使用的是FOSUserBundle,则应使用:

use \Blogger\BlogBundle\Entity\User;

$userManager = $this->get('fos_user_manager');

$password = 'password';
$user = new User();
$user->setPlainPassword($password);

$userManager->updateUser($user, true); // second argument tells user manager to flush

答案 1 :(得分:1)

在查看了bcrypt的Symfony2.3实现的源代码之后,他们使用了一个名为hash_algorithm()的函数,它似乎产生与crypt()不同的结果。两者都使用$ 2y $版本的bcrypt并且我已经将两种算法的成本设置为13 ...但是,为了设置密码而执行以下操作更加一致:

$user->setPassword(password_hash($user->getPassword(), PASSWORD_BCRYPT, array('cost' => 13)));

这行代码似乎解决了我的问题。最好的部分是我甚至不用再生盐了。