ModernPasswordHasher.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. * @author Mark Scherer
  15. * @license http://opensource.org/licenses/mit-license.php MIT
  16. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/
  17. */
  18. class ModernPasswordHasher extends AbstractPasswordHasher {
  19. /**
  20. * Constructor
  21. *
  22. * @param array $config Array of config.
  23. */
  24. public function __construct($config = []) {
  25. if (!function_exists('password_hash')) {
  26. throw new CakeException('password_hash() is not available.');
  27. }
  28. parent::__construct($config);
  29. }
  30. /**
  31. * Default config for this object.
  32. *
  33. * @var array
  34. */
  35. protected $_config = [
  36. 'salt' => null,
  37. 'cost' => 10,
  38. 'hashType' => PASSWORD_BCRYPT
  39. ];
  40. /**
  41. * Generates password hash.
  42. *
  43. * @param string $password Plain text password to hash.
  44. * @return string Password hash.
  45. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#using-bcrypt-for-passwords
  46. */
  47. public function hash($password) {
  48. $options = ['cost' => $this->_config['cost'], 'salt' => $this->_config['salt']];
  49. $options = array_filter($options);
  50. return password_hash($password, $this->_config['hashType'], $options);
  51. }
  52. /**
  53. * Check hash. Generate hash for user provided password and check against existing hash.
  54. *
  55. * @param string $password Plain text password to hash.
  56. * @param string Existing hashed password.
  57. * @return bool True if hashes match else false.
  58. */
  59. public function check($password, $hashedPassword) {
  60. return password_verify($password, $hashedPassword);
  61. }
  62. /**
  63. * Returns true if the password need to be rehashed, due to the password being
  64. * created with anything else than the passwords currently generated by this class.
  65. *
  66. * @param string $password The password hash to verify.
  67. * @return bool True if it needs rehashing.
  68. */
  69. public function needsRehash($currentHash) {
  70. return password_needs_rehash($currentHash, $this->_config['hashType']);
  71. }
  72. }