3 namespace Wallabag\CoreBundle\Security\Authentication\Encoder
;
5 use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder
;
6 use Symfony\Component\Security\Core\Exception\BadCredentialsException
;
9 * This override just add en extra variable (username) to be able to salt the password
10 * the way Wallabag v1 does. It will avoid to break compatibility with Wallabag v1
13 class WallabagPasswordEncoder
extends BasePasswordEncoder
16 private $encodeHashAsBase64;
18 private $username = null;
23 * @param string $algorithm The digest algorithm to use
24 * @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
25 * @param int $iterations The number of iterations to use to stretch the password hash
27 public function __construct($algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000)
29 $this->algorithm
= $algorithm;
30 $this->encodeHashAsBase64
= $encodeHashAsBase64;
31 $this->iterations
= $iterations;
34 public function setUsername($username)
36 $this->username
= $username;
42 public function encodePassword($raw, $salt)
44 if (null === $this->username
) {
45 throw new \
LogicException('We can not check the password without a username.');
48 if ($this->isPasswordTooLong($raw)) {
49 throw new BadCredentialsException('Invalid password.');
52 if (!in_array($this->algorithm
, hash_algos(), true)) {
53 throw new \
LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm
));
56 $salted = $this->mergePasswordAndSalt($raw, $salt);
57 $digest = hash($this->algorithm
, $salted, true);
60 for ($i = 1; $i < $this->iterations
; $i++
) {
61 $digest = hash($this->algorithm
, $digest.$salted, true);
64 return $this->encodeHashAsBase64
? base64_encode($digest) : bin2hex($digest);
70 * We inject the username inside the salted password
72 protected function mergePasswordAndSalt($password, $salt)
78 return $password.$this->username
.$salt;
84 public function isPasswordValid($encoded, $raw, $salt)
86 return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));