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.
12 class WallabagPasswordEncoder
extends BasePasswordEncoder
15 private $encodeHashAsBase64;
17 private $username = null;
22 * @param string $algorithm The digest algorithm to use
23 * @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
24 * @param int $iterations The number of iterations to use to stretch the password hash
26 public function __construct($algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000)
28 $this->algorithm
= $algorithm;
29 $this->encodeHashAsBase64
= $encodeHashAsBase64;
30 $this->iterations
= $iterations;
33 public function setUsername($username)
35 $this->username
= $username;
41 public function encodePassword($raw, $salt)
43 if ($this->isPasswordTooLong($raw)) {
44 throw new BadCredentialsException('Invalid password.');
47 if (!in_array($this->algorithm
, hash_algos(), true)) {
48 throw new \
LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm
));
51 $salted = $this->mergePasswordAndSalt($raw, $salt);
52 $digest = hash($this->algorithm
, $salted, true);
55 for ($i = 1; $i < $this->iterations
; $i++
) {
56 $digest = hash($this->algorithm
, $digest.$salted, true);
59 return $this->encodeHashAsBase64
? base64_encode($digest) : bin2hex($digest);
65 * We inject the username inside the salted password
67 protected function mergePasswordAndSalt($password, $salt)
69 if (null === $this->username
) {
70 throw new \
LogicException('We can not check the password without a username.');
77 return $password.$this->username
.$salt;
83 public function isPasswordValid($encoded, $raw, $salt)
85 return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));