MessageDigestPasswordEncoder.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Core\Encoder;
  11. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  12. /**
  13. * MessageDigestPasswordEncoder uses a message digest algorithm.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class MessageDigestPasswordEncoder extends BasePasswordEncoder
  18. {
  19. private $algorithm;
  20. private $encodeHashAsBase64;
  21. private $iterations = 1;
  22. private $encodedLength = -1;
  23. /**
  24. * @param string $algorithm The digest algorithm to use
  25. * @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
  26. * @param int $iterations The number of iterations to use to stretch the password hash
  27. */
  28. public function __construct(string $algorithm = 'sha512', bool $encodeHashAsBase64 = true, int $iterations = 5000)
  29. {
  30. $this->algorithm = $algorithm;
  31. $this->encodeHashAsBase64 = $encodeHashAsBase64;
  32. try {
  33. $this->encodedLength = \strlen($this->encodePassword('', 'salt'));
  34. } catch (\LogicException $e) {
  35. // ignore algorithm not supported
  36. }
  37. $this->iterations = $iterations;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function encodePassword(string $raw, ?string $salt)
  43. {
  44. if ($this->isPasswordTooLong($raw)) {
  45. throw new BadCredentialsException('Invalid password.');
  46. }
  47. if (!\in_array($this->algorithm, hash_algos(), true)) {
  48. throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
  49. }
  50. $salted = $this->mergePasswordAndSalt($raw, $salt);
  51. $digest = hash($this->algorithm, $salted, true);
  52. // "stretch" hash
  53. for ($i = 1; $i < $this->iterations; ++$i) {
  54. $digest = hash($this->algorithm, $digest.$salted, true);
  55. }
  56. return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest);
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function isPasswordValid(string $encoded, string $raw, ?string $salt)
  62. {
  63. if (\strlen($encoded) !== $this->encodedLength || false !== strpos($encoded, '$')) {
  64. return false;
  65. }
  66. return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
  67. }
  68. }