Dr.Knowitall
Dr.Knowitall

Reputation: 10468

How to get symfony2 security BCRYPT encoder to work with php crypt() function

I am using bcrypt to hash my passwords and it seems that symfony2 authentication system is not production the same hash as php's native crypt function. Bellow is the salt that I am generating for my user password:

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

In my security.yml file I am simply doing:

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

Is there any reason why the two encoding methods would generate different hashes? The library I am using is ircmaxell/password-compat.

Upvotes: 1

Views: 9934

Answers (2)

Samuel Gordalina
Samuel Gordalina

Reputation: 81

Best way to use this within Symfony2 is to use 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);

If you are using FOSUserBundle, you should use:

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

Upvotes: 3

Dr.Knowitall
Dr.Knowitall

Reputation: 10468

After reviewing the source code for Symfony2.3 implementation of bcrypt, they use a function called hash_algorithm() and it seems to yield different results than crypt(). Both use $2y$ versions of bcrypt and I had set the cost for both algorithms to 13 ... however it is more consistent to do the following for setting passwords instead:

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

That line of code seemed to fix my problem. The best part is that I don't even have to generate my salt any more.

Upvotes: 1

Related Questions