-
-
Save SamFleming/2827901 to your computer and use it in GitHub Desktop.
PHP PBKDF2 implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* PHP PBKDF2 implementation | |
* | |
* PBKDF2 is a key derivation function defined in RFC2898. It's used to | |
* generate longer and more secure passwords from short, human-entered | |
* passwords. The number of rounds can be increased to keep ahead of | |
* improvements in CPU/GPU performance. | |
* | |
* You should use a different salt for each password (it's safe to store it | |
* alongside your generated password; much safer than using the same salt for | |
* multiple passwords, anyway). | |
* | |
* This function is slow; that's intentional! You should use at least 5000 | |
* rounds in 2011. | |
* | |
* For more information see: | |
* - http://en.wikipedia.org/wiki/PBKDF2 | |
* - http://www.ietf.org/rfc/rfc2898.txt | |
* | |
* This implementation is very slightly modified from the one found here: | |
* http://www.php.net/manual/en/function.hash-hmac.php#101540 | |
* | |
* The variable names have been made readable, some have sensible defaults, | |
* and the output is Base64 encoded | |
*/ | |
function hash_pbkdf2($password, $salt, $rounds = 5000, $key_length = 32, $a = 'sha256', $start=0) | |
{ | |
// Key blocks to compute | |
$kb = $start+$key_length; | |
// Derived key | |
$dk = ''; | |
// Create key | |
for ($block=1; $block<=$kb; $block++) | |
{ | |
// Initial hash for this block | |
$ib = $h = hash_hmac($a, $salt . pack('N', $block), $password, true); | |
// Perform block iterations | |
for ($i=1; $i<$rounds; $i++) | |
{ | |
// XOR each iteration | |
$ib ^= ($h = hash_hmac($a, $h, $password, true)); | |
} | |
// Append iterated block | |
$dk .= $ib; | |
} | |
// Return derived key of correct length | |
return base64_encode(substr($dk, $start, $key_length)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment