ModernPasswordHasher.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. App::uses('AbstractPasswordHasher', 'Controller/Component/Auth');
  3. /**
  4. * Modern password hashing class for PHP5.5+.
  5. * A backport of the 3.x DefaultPasswordHasher class.
  6. *
  7. * This requires either PHP5.5+ or the password_hash() shim from
  8. * https://github.com/ircmaxell/password_compat
  9. * If you don't use composer, you can also directly use the class in this repo:
  10. * require CakePlugin::path('Tools') . 'Lib/Bootstrap/Password.php';
  11. * You would then require it in your bootstrap.php.
  12. * But the preferred way would be a composer dependency.
  13. */
  14. class ModernPasswordHasher extends AbstractPasswordHasher {
  15. /**
  16. * Constructor
  17. *
  18. * @param array $config Array of config.
  19. */
  20. public function __construct($config = array()) {
  21. if (!function_exists('password_hash')) {
  22. throw new CakeException('password_hash() is not available.');
  23. }
  24. parent::__construct($config);
  25. }
  26. /**
  27. * Default config for this object.
  28. *
  29. * @var array
  30. */
  31. protected $_config = array(
  32. 'salt' => null,
  33. 'cost' => 10,
  34. 'hashType' => PASSWORD_BCRYPT
  35. );
  36. /**
  37. * Generates password hash.
  38. *
  39. * @param string $password Plain text password to hash.
  40. * @return string Password hash
  41. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#using-bcrypt-for-passwords
  42. */
  43. public function hash($password) {
  44. $options = array('cost' => $this->_config['cost'], 'salt' => $this->_config['salt']);
  45. $options = array_filter($options);
  46. return password_hash($password, $this->_config['hashType'], $options);
  47. }
  48. /**
  49. * Check hash. Generate hash for user provided password and check against existing hash.
  50. *
  51. * @param string $password Plain text password to hash.
  52. * @param string Existing hashed password.
  53. * @return bool True if hashes match else false.
  54. */
  55. public function check($password, $hashedPassword) {
  56. return password_verify($password, $hashedPassword);
  57. }
  58. /**
  59. * Returns true if the password need to be rehashed, due to the password being
  60. * created with anything else than the passwords generated by this class.
  61. *
  62. * @param string $password The password to verify
  63. * @return bool
  64. */
  65. public function needsRehash($password) {
  66. return password_needs_rehash($password, $this->_config['hashType']);
  67. }
  68. }