functions.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. if (!function_exists('hash_pbkdf2')) {
  3. /**
  4. * Based on pbkdf2() from https://defuse.ca/php-pbkdf2.htm. Made signature-compatible with hash_pbkdf2() in PHP5.5
  5. *
  6. * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
  7. * $algorithm - The hash algorithm to use. Recommended: SHA256
  8. * $password - The password.
  9. * $salt - A salt that is unique to the password.
  10. * $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
  11. * $key_length - The length of the derived key in bytes.
  12. * $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
  13. * Returns: A $key_length-byte key derived from the password and salt.
  14. *
  15. * Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
  16. *
  17. * This implementation of PBKDF2 was originally created by https://defuse.ca
  18. * With improvements by http://www.variations-of-shadow.com
  19. */
  20. function hash_pbkdf2($algorithm, $password, $salt, $count, $key_length = 0, $raw_output = false)
  21. {
  22. $algorithm = strtolower($algorithm);
  23. if(!in_array($algorithm, hash_algos(), true))
  24. die('PBKDF2 ERROR: Invalid hash algorithm.');
  25. if($count <= 0 || $key_length <= 0)
  26. die('PBKDF2 ERROR: Invalid parameters.');
  27. $hash_length = strlen(hash($algorithm, "", true));
  28. $block_count = ceil($key_length / $hash_length);
  29. $output = "";
  30. for($i = 1; $i <= $block_count; $i++) {
  31. // $i encoded as 4 bytes, big endian.
  32. $last = $salt . pack("N", $i);
  33. // first iteration
  34. $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
  35. // perform the other $count - 1 iterations
  36. for ($j = 1; $j < $count; $j++) {
  37. $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
  38. }
  39. $output .= $xorsum;
  40. }
  41. if($raw_output)
  42. return substr($output, 0, $key_length);
  43. else
  44. return bin2hex(substr($output, 0, $key_length));
  45. }
  46. }