Created
April 8, 2013 15:54
-
-
Save xeoncross/5337905 to your computer and use it in GitHub Desktop.
hash a string using md5 or sha1 and compress the length by converting from base 16 (hex) to base 64.
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
<?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
Thanks for that, I updated to this shorter, URL-safe version:
Which prints: