hasher.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php namespace Laravel\Security; use Laravel\Str;
  2. class Hasher {
  3. /**
  4. * Hash a password using the Bcrypt hashing scheme.
  5. *
  6. * Bcrypt provides a future-proof hashing algorithm by allowing the number of "rounds"
  7. * to be increased, thus increasing the time is takes to generate the hashed value.
  8. * The longer is takes to generate the hash, the more impractical a rainbow table
  9. * attack against the hashes becomes.
  10. *
  11. * <code>
  12. * // Create a Bcrypt hash of a value
  13. * $hash = Hasher::hash('secret');
  14. *
  15. * // Use a specified number of iterations when creating the hash
  16. * $hash = Hasher::hash('secret', 12);
  17. * </code>
  18. *
  19. * @param string $value
  20. * @param int $rounds
  21. * @return string
  22. */
  23. public static function hash($value, $rounds = 8)
  24. {
  25. return crypt($value, '$2a$'.str_pad($rounds, 2, '0', STR_PAD_LEFT).'$'.static::salt());
  26. }
  27. /**
  28. * Determine if an unhashed value matches a given Bcrypt hash.
  29. *
  30. * Since the number of rounds is included in the Bcrypt hash, it is not
  31. * necessary to specify the rounds when calling this method.
  32. *
  33. * @param string $value
  34. * @param string $hash
  35. * @return bool
  36. */
  37. public static function check($value, $hash)
  38. {
  39. return crypt($value, $hash) === $hash;
  40. }
  41. /**
  42. * Get a salt for use during Bcrypt hashing.
  43. *
  44. * @return string
  45. */
  46. protected static function salt()
  47. {
  48. // If OpenSSL is installed, we will use it to gather random bytes for generating
  49. // the salt value. Otherwise, we will use the Str::random method. Bcrypt expects
  50. // the salt to be a 22 character alpha-numeric string. The salt may also contain
  51. // dots, plus signs, and forward slashes.
  52. if (function_exists('openssl_random_pseudo_bytes'))
  53. {
  54. return substr(strtr(base64_encode(openssl_random_pseudo_bytes(16)), '+', '.'), 0 , 22);
  55. }
  56. return substr(str_replace('+', '.', base64_encode(Str::random(40))), 0, 22);
  57. }
  58. }