Skip to content

Instantly share code, notes, and snippets.

@suvozy
Forked from xeoncross/base64_hash.php
Last active August 29, 2015 14:06
Show Gist options
  • Save suvozy/90939c8e5aff83ccceff to your computer and use it in GitHub Desktop.
Save suvozy/90939c8e5aff83ccceff to your computer and use it in GitHub Desktop.
<?php
/*
* Because we are removing the ending `=` padding we will have a string length of
* md5 <= 24
* sha1 <= 28
*
* Probably should just remove the code that trims the equal sign since it's kind of pointless....
*/
$value = microtime(TRUE);
function base64_hash($data, $algo = 'md5')
{
// also remove the extra `=` trailing padding.
return rtrim(base64_encode(pack('H*', $algo($data))), '=');
}
function base64_hash_restore($hash)
{
// If the length isn't a multiple of 4 characters, add = characters until it is
$number = abs(4 - (strlen($hash) % 4));
return $hash . str_repeat('=', $number === 4 ? 0 : $number);
}
$hash = base64_hash($value);
foreach (array('md5', 'sha1') as $algo) {
print $algo . "\n";
for ($i=0; $i < 5; $i++) {
print $hash . ' + ' . $i . ' = ' . (strlen($hash) + $i) . "\n";
$new = base64_hash_restore($hash . str_repeat('=', $i), $algo);
print $new . ' : ' . strlen($new). "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment