2013-06-23 81 views
1

一起使用我正在使用bcrypt來哈希我的密碼,似乎symfony2身份驗證系統不是生產與php的本地crypt函數相同的哈希值。貝婁是我產生了我的用戶密碼的鹽:我只是做如何獲得symfony2安全BCRYPT編碼器與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。

+0

請您提供用於測試的crypt函數的代碼。也許這是迭代次數? – nifr

+1

Symfony的最新版本?另外,爲什麼你要手動設置鹽?另外,爲什麼你以這種可怕的方式產生鹽? Symfony會爲你做這個。你爲什麼試圖讓它比需要的更困難?證明:[Symfony的源代碼](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Encoder/BCryptPasswordEncoder.php#L48) – ircmaxell

+0

這是一個預期的行爲,每次都會得到不同的散列值,因爲每次計算都會生成一個不同的(隨機)鹽。攻擊者通過這種方式無法判斷兩個用戶是否輸入了相同的密碼。如果你想測試哈希,那麼只需測試驗證失敗/成功。 – martinstoeckli

回答

1

在回顧了bcrypt的Symfony2.3實現的源代碼之後,他們使用了一個名爲hash_algorithm()的函數,它看起來會產生與crypt()不同的結果。 bcrypt的兩個使用$ 2Y $版本,我已經設置了兩種算法,以13中的成本......但它是更一致做了設置密碼不要使用以下:

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

這行代碼似乎解決我的問題。最好的部分是,我甚至不必再生成我的鹽。

+0

爲什麼你手動散列密碼呢? – ircmaxell

+0

我不知道更好。 –

3

在Symfony2中使用它的最佳方式是使用獲取編碼器。

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