Skip to content

Instantly share code, notes, and snippets.

@xqus
Created July 10, 2011 20:21
Show Gist options
  • Select an option

  • Save xqus/1074931 to your computer and use it in GitHub Desktop.

Select an option

Save xqus/1074931 to your computer and use it in GitHub Desktop.
Creating an encryption key from a secret using PHP
<?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