Skip to content

Instantly share code, notes, and snippets.

@xqus
Created November 7, 2011 16:59
Show Gist options
  • Save xqus/1345520 to your computer and use it in GitHub Desktop.
Save xqus/1345520 to your computer and use it in GitHub Desktop.
phpSec key history
<?php
/* Check key size. */
$keySize = strlen($key);
$keySizes = mcrypt_enc_get_supported_key_sizes($td);
if(count($keySizes) > 0) {
/* Encryption method requires a specific key size. */
if(!in_array($keySize, $keySizes)) {
phpsec::error('Key is out of range. Should be one of: '. var_export($keySizes ,1));
return false;
}
} else {
/* No spsecific size is needed. */
if($keySize == 0 || $keySize > mcrypt_enc_get_key_size($td)) {
phpsec::error('Key is out of range. Should be: 1 - ' . mcrypt_enc_get_key_size($td).' bytes.');
return false;
}
}
<?php
/**
* Get a key from a secret.
* What we do is create two different hashes from the secret, combine them
* and pick out the number of characters we need.
* We used the raw binary output of the hash function for maximum
* bit strength (we have 255 chars to choose from, instead of 16).
*
* @param string $secret
* The secret to generate a key from.
*
* @param integer $ks
* The key size.
*
* @return binary
* Key created from secret.
*/
private static function getKey($secret, $ks) {
/* Split the secret into two parts. */
$secretSplit = floor(strlen($secret));
$secret1 = substr($secret, 0, $secretSplit);
$secret2 = substr($secret, $secretSplit);
/* Hash the two parts seperatly and return the result in raw format. */
$key1 = hash('sha256', $secret1, true);
$key2 = hash('sha256', $secret2, true);
/* Return the part of the key we need. */
return substr($key2.$key1, 0, $ks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment