hash.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php namespace Laravel;
  2. class Hash {
  3. /**
  4. * Hash a password using the Bcrypt hashing scheme.
  5. *
  6. * Bcrypt provides a future-proof hashing algorithm by allowing the number of
  7. * "rounds" to be increased, thus increasing the time it takes to generate the
  8. * hashed value. The longer it takes takes to generate the hash, the more
  9. * impractical a rainbow table attack against the hashes becomes.
  10. *
  11. * <code>
  12. * // Create a Bcrypt hash of a value
  13. * $hash = Hash::make('secret');
  14. *
  15. * // Use a specified number of iterations when creating the hash
  16. * $hash = Hash::make('secret', 12);
  17. * </code>
  18. *
  19. * @param string $value
  20. * @param int $rounds
  21. * @return string
  22. */
  23. public static function make($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. * @param string $value
  31. * @param string $hash
  32. * @return bool
  33. */
  34. public static function check($value, $hash)
  35. {
  36. return crypt($value, $hash) === $hash;
  37. }
  38. /**
  39. * Get a salt for use during Bcrypt hashing.
  40. *
  41. * @return string
  42. */
  43. protected static function salt()
  44. {
  45. // Bcrypt expects the salt to be 22 base64 encoded characters, including dots
  46. // and slashes. We will get rid of the plus signs included in the base64 data
  47. // and replace them with dots. OpenSSL will be used if available, since it is
  48. // more random, otherwise we will fallback on Str::random.
  49. if (function_exists('openssl_random_pseudo_bytes'))
  50. {
  51. $bytes = openssl_random_pseudo_bytes(16);
  52. return substr(strtr(base64_encode($bytes), '+', '.'), 0 , 22);
  53. }
  54. return substr(str_replace('+', '.', base64_encode(Str::random(40))), 0, 22);
  55. }
  56. }