BcryptHasher.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Illuminate\Hashing;
  3. use RuntimeException;
  4. use Illuminate\Contracts\Hashing\Hasher as HasherContract;
  5. class BcryptHasher extends AbstractHasher implements HasherContract
  6. {
  7. /**
  8. * The default cost factor.
  9. *
  10. * @var int
  11. */
  12. protected $rounds = 10;
  13. /**
  14. * Create a new hasher instance.
  15. *
  16. * @param array $options
  17. * @return void
  18. */
  19. public function __construct(array $options = [])
  20. {
  21. $this->rounds = $options['rounds'] ?? $this->rounds;
  22. }
  23. /**
  24. * Hash the given value.
  25. *
  26. * @param string $value
  27. * @param array $options
  28. * @return string
  29. *
  30. * @throws \RuntimeException
  31. */
  32. public function make($value, array $options = [])
  33. {
  34. $hash = password_hash($value, PASSWORD_BCRYPT, [
  35. 'cost' => $this->cost($options),
  36. ]);
  37. if ($hash === false) {
  38. throw new RuntimeException('Bcrypt hashing not supported.');
  39. }
  40. return $hash;
  41. }
  42. /**
  43. * Check if the given hash has been hashed using the given options.
  44. *
  45. * @param string $hashedValue
  46. * @param array $options
  47. * @return bool
  48. */
  49. public function needsRehash($hashedValue, array $options = [])
  50. {
  51. return password_needs_rehash($hashedValue, PASSWORD_BCRYPT, [
  52. 'cost' => $this->cost($options),
  53. ]);
  54. }
  55. /**
  56. * Set the default password work factor.
  57. *
  58. * @param int $rounds
  59. * @return $this
  60. */
  61. public function setRounds($rounds)
  62. {
  63. $this->rounds = (int) $rounds;
  64. return $this;
  65. }
  66. /**
  67. * Extract the cost value from the options array.
  68. *
  69. * @param array $options
  70. * @return int
  71. */
  72. protected function cost(array $options = [])
  73. {
  74. return $options['rounds'] ?? $this->rounds;
  75. }
  76. }