Created
February 3, 2014 22:09
-
-
Save narfbg/8793435 to your computer and use it in GitHub Desktop.
Experimental HKDF implementation for CodeIgniter's encryption class
This file contains hidden or 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
/** | |
* HKDF | |
* | |
* @link https://tools.ietf.org/rfc/rfc5869.txt | |
* @param $key Input key | |
* @param $digest A SHA-2 hashing algorithm | |
* @param $salt Optional salt | |
* @param $length Output length (defaults to the selected digest size) | |
* @param $info Optional context/application-specific info | |
* @return string A pseudo-random key | |
*/ | |
function hkdf($key, $digest = 'sha512', $salt = NULL, $length = NULL, $info = '') | |
{ | |
if ( ! in_array($digest, array('sha224', 'sha256', 'sha384', 'sha512'), TRUE)) | |
{ | |
return FALSE; | |
} | |
$digest_length = substr($digest, 3) / 8; | |
if (empty($length) OR ! is_int($length)) | |
{ | |
$length = $digest_length; | |
} | |
elseif ($length > (255 * $digest_length)) | |
{ | |
return FALSE; | |
} | |
isset($salt) OR $salt = str_repeat("\0", substr($digest, 3) / 8); | |
$prk = hash_hmac($digest, $key, $salt, TRUE); | |
$key = ''; | |
for ($key_block = '', $block_index = 1; strlen($key) < $length; $block_index++) | |
{ | |
$key_block = hash_hmac($digest, $key_block.$info.chr($block_index), $prk, TRUE); | |
$key .= $key_block; | |
} | |
return substr($key, 0, $length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test cases appendix A1 to A3 success (e.g. $R[1]==$OKM )