hasher.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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
  7. * number of "rounds" to be increased, thus increasing the time it
  8. * takes to generate the hashed value. The longer it takes takes
  9. * to generate the hash, the more impractical a rainbow table
  10. * attack against the hashes becomes.
  11. *
  12. * <code>
  13. * // Create a Bcrypt hash of a value
  14. * $hash = Hasher::hash('secret');
  15. *
  16. * // Use a specified number of iterations when creating the hash
  17. * $hash = Hasher::hash('secret', 12);
  18. * </code>
  19. *
  20. * @param string $value
  21. * @param int $rounds
  22. * @return string
  23. */
  24. public static function hash($value, $rounds = 8)
  25. {
  26. return crypt($value, '$2a$'.str_pad($rounds, 2, '0', STR_PAD_LEFT).'$'.static::salt());
  27. }
  28. /**
  29. * Determine if an unhashed value matches a given Bcrypt hash.
  30. *
  31. * @param string $value
  32. * @param string $hash
  33. * @return bool
  34. */
  35. public static function check($value, $hash)
  36. {
  37. return crypt($value, $hash) === $hash;
  38. }
  39. /**
  40. * Get a salt for use during Bcrypt hashing.
  41. *
  42. * Bcrypt expects salts to be 22 alpha-numeric characters including
  43. * dots and forward slashes. OpenSSL will be used if available and
  44. * the Str::random method will be used if it isn't.
  45. *
  46. * @return string
  47. */
  48. protected static function salt()
  49. {
  50. if (function_exists('openssl_random_pseudo_bytes'))
  51. {
  52. return substr(strtr(base64_encode(openssl_random_pseudo_bytes(16)), '+', '.'), 0 , 22);
  53. }
  54. return substr(str_replace('+', '.', base64_encode(Str::random(40))), 0, 22);
  55. }
  56. }