最近在研究bcrypt跟PBKDF2, 这是找到的代码.
- /*
- * PBKDF2 key derivation function as defined by RSA's PKCS #5:
- * $algorithm - The hash algorithm to use. Recommended: SHA256
- * $password - The password.
- * $salt - A salt that is unique to the password.
- * $count - Iteration count. Higher = better. Recommended: At least 1024.
- * $key_length - The length of the derived key in BYTES.
- * Returns: A $key_length-byte key derived from the password and salt (in binary).
- *
- * Test vectors can be found here:
- */
- function pbkdf2($algorithm, $password, $salt, $count, $key_length)
- {
- $algorithm = strtolower($algorithm);
- if(!in_array($algorithm, hash_algos(), true))
- die('PBKDF2 ERROR: Invalid hash algorithm.');
- if($count < 0 || $key_length < 0)
- die('PBKDF2 ERROR: Invalid parameters.');
- if($key_length > 4294967295)
- die('PBKDF2 ERROR: Derived key too long.');
- $hLen = strlen(hash($algorithm, "", true));
- $numBlocks = (int)ceil((double)$key_length / $hLen);
- $output = "";
- for($i = 1; $i <= $numBlocks; $i++)
- {
- $output .= pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen);
- }
- return substr($output, 0, $key_length);
- }
- /*
- * The pseudorandom function used by PBKDF2.
- * Definition:
- */
- function pbkdf2_f($password, $salt, $count, $i, $algorithm, $hLen)
- {
- //$i encoded as 4 bytes, big endian.
- $last = $salt . chr(($i >> 24) % 256) . chr(($i >> 16) % 256) . chr(($i >> 8) % 256) . chr($i % 256);
- $xorsum = "";
- for($r = 0; $r < $count; $r++)
- {
- $u = hash_hmac($algorithm, $last, $password, true);
- $last = $u;
- if(empty($xorsum))
- $xorsum = $u;
- else
- {
- for($c = 0; $c < $hLen; $c++)
- {
- $xorsum[$c] = chr(ord(substr($xorsum, $c, 1)) ^ ord(substr($u, $c, 1)));
- }
- }
- }
- return $xorsum;
- }
阅读(4278) | 评论(0) | 转发(0) |