hash.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php namespace Laravel;
  2. class Hash {
  3. /**
  4. * Hash a password using the Bcrypt hashing scheme.
  5. *
  6. * <code>
  7. * // Create a Bcrypt hash of a value
  8. * $hash = Hash::make('secret');
  9. *
  10. * // Use a specified number of iterations when creating the hash
  11. * $hash = Hash::make('secret', 12);
  12. * </code>
  13. *
  14. * @param string $value
  15. * @param int $rounds
  16. * @return string
  17. */
  18. public static function make($value, $rounds = 8)
  19. {
  20. $work = str_pad($rounds, 2, '0', STR_PAD_LEFT);
  21. // Bcrypt expects the salt to be 22 base64 encoded characters including
  22. // dots and slashes. We will get rid of the plus signs included in the
  23. // base64 data and replace them with dots. OpenSSL will be used if it
  24. // is available on the server.
  25. if (function_exists('openssl_random_pseudo_bytes'))
  26. {
  27. $salt = openssl_random_pseudo_bytes(16);
  28. }
  29. else
  30. {
  31. $salt = Str::random(40);
  32. }
  33. $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
  34. return crypt($value, '$2a$'.$work.'$'.$salt);
  35. }
  36. /**
  37. * Determine if an unhashed value matches a Bcrypt hash.
  38. *
  39. * @param string $value
  40. * @param string $hash
  41. * @return bool
  42. */
  43. public static function check($value, $hash)
  44. {
  45. return crypt($value, $hash) === $hash;
  46. }
  47. }