ModernPasswordHasher.php 2.2 KB

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