ModernPasswordHasher.php 2.1 KB

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