From d91691573f108422cc2080462af35ebd62dc93fb Mon Sep 17 00:00:00 2001 From: Jeremy Date: Sun, 8 Feb 2015 21:47:36 +0100 Subject: Add custom auth encoder & provider These custom classes allow Wallabag v2 to be compatible with Wallabag v1 salted password --- .../Encoder/WallabagPasswordEncoder.php | 88 ++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php (limited to 'src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php') diff --git a/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php b/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php new file mode 100644 index 00000000..56f1affe --- /dev/null +++ b/src/Wallabag/CoreBundle/Security/Authentication/Encoder/WallabagPasswordEncoder.php @@ -0,0 +1,88 @@ +algorithm = $algorithm; + $this->encodeHashAsBase64 = $encodeHashAsBase64; + $this->iterations = $iterations; + } + + public function setUsername($username) + { + $this->username = $username; + } + + /** + * {@inheritdoc} + */ + public function encodePassword($raw, $salt) + { + if (null === $this->username) { + throw new \LogicException('We can not check the password without a username.'); + } + + if ($this->isPasswordTooLong($raw)) { + throw new BadCredentialsException('Invalid password.'); + } + + if (!in_array($this->algorithm, hash_algos(), true)) { + throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm)); + } + + $salted = $this->mergePasswordAndSalt($raw, $salt); + $digest = hash($this->algorithm, $salted, true); + + // "stretch" hash + for ($i = 1; $i < $this->iterations; $i++) { + $digest = hash($this->algorithm, $digest.$salted, true); + } + + return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest); + } + + /** + * {@inheritdoc} + * + * We inject the username inside the salted password + */ + protected function mergePasswordAndSalt($password, $salt) + { + if (empty($salt)) { + return $password; + } + + return $password.$this->username.$salt; + } + + /** + * {@inheritdoc} + */ + public function isPasswordValid($encoded, $raw, $salt) + { + return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt)); + } +} -- cgit v1.2.3