hash.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.
  24. if (function_exists('openssl_random_pseudo_bytes'))
  25. {
  26. $salt = openssl_random_pseudo_bytes(16);
  27. }
  28. else
  29. {
  30. $salt = Str::random(40);
  31. }
  32. $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
  33. return crypt($value, '$2a$'.$work.'$'.$salt);
  34. }
  35. /**
  36. * Determine if an unhashed value matches a Bcrypt hash.
  37. *
  38. * @param string $value
  39. * @param string $hash
  40. * @return bool
  41. */
  42. public static function check($value, $hash)
  43. {
  44. return crypt($value, $hash) === $hash;
  45. }
  46. }