modpbkdf2.class.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of MODX Revolution.
  4. *
  5. * Copyright (c) MODX, LLC. All Rights Reserved.
  6. *
  7. * For complete copyright and license information, see the COPYRIGHT and LICENSE
  8. * files found in the top-level directory of this distribution.
  9. */
  10. /**
  11. * A PBKDF2 implementation of modHash.
  12. *
  13. * {@inheritdoc}
  14. *
  15. * @package modx
  16. * @subpackage hashing
  17. */
  18. class modPBKDF2 extends modHash {
  19. /**
  20. * Generate a hash of a string using the RSA PBKDFA2 specification.
  21. *
  22. * The following options are available:
  23. * - salt (required): a valid, non-empty string to salt the hashes
  24. * - iterations: the number of iterations per block, default is 1000 (< 1000 not recommended)
  25. * - derived_key_length: the size of the derived key to generate, default is 32
  26. * - algorithm: the hash algorithm to use, default is sha256
  27. * - raw_output: if true, returns binary output, otherwise derived key is base64_encode()'d; default is false
  28. *
  29. * @param string $string A string to generate a secure hash from.
  30. * @param array $options An array of options to be passed to the hash implementation.
  31. * @return mixed The hash result or false on failure.
  32. */
  33. public function hash($string, array $options = array()) {
  34. $derivedKey = false;
  35. $salt = $this->getOption('salt', $options, false);
  36. if (is_string($salt) && strlen($salt) > 0) {
  37. $iterations = (integer) $this->getOption('iterations', $options, 1000);
  38. $derivedKeyLength = (integer) $this->getOption('derived_key_length', $options, 32);
  39. $algorithm = $this->getOption('algorithm', $options, 'sha256');
  40. $hashLength = strlen(hash($algorithm, null, true));
  41. $keyBlocks = ceil($derivedKeyLength / $hashLength);
  42. $derivedKey = '';
  43. for ($block = 1; $block <= $keyBlocks; $block++) {
  44. $hashBlock = $hb = hash_hmac($algorithm, $salt . pack('N', $block), $string, true);
  45. for ($blockIteration = 1; $blockIteration < $iterations; $blockIteration++) {
  46. $hashBlock ^= ($hb = hash_hmac($algorithm, $hb, $string, true));
  47. }
  48. $derivedKey .= $hashBlock;
  49. }
  50. $derivedKey = substr($derivedKey, 0, $derivedKeyLength);
  51. if (!$this->getOption('raw_output', $options, false)) {
  52. $derivedKey = base64_encode($derivedKey);
  53. }
  54. } else {
  55. $this->host->modx->log(modX::LOG_LEVEL_ERROR, "PBKDF2 requires a valid salt string.", '', __METHOD__, __FILE__, __LINE__);
  56. }
  57. return $derivedKey;
  58. }
  59. }