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