Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created April 8, 2013 15:54
Show Gist options
  • Save xeoncross/5337905 to your computer and use it in GitHub Desktop.
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.
<?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";
}
}
@polonskiy
Copy link

You can replace pack('H*', $algo($data)) with $algo($data, 1).

@xeoncross
Copy link
Author

Thanks for that, I updated to this shorter, URL-safe version:

<?phpfunction base64_url_encode($string = NULL)
{
    return strtr(base64_encode($string), '+/=', '-_~');
}

function base64_url_decode($string = NULL)
{
    return base64_decode(strtr($string, '-_~', '+/='));
}

header('Content-Type: text/plain;');
$string = 'This is the text that I want to hash right here';

print $string . "\n";
print 'MD5          : ' . md5($string) . "\n";
print 'MD5_64_url   : ' . base64_url_encode(md5($string, true)) . "\n";
print 'SHA1         : ' . sha1($string) . "\n";
print 'SHA1_64_url  : ' . base64_url_encode(sha1($string, true)) . "\n";
print 'SHA256       : ' . hash('SHA256', $string) . "\n";
print 'SHA256_64    : ' . base64_encode(hash('SHA256', $string, true)) . "\n";
print 'SHA256_64_url: ' . base64_url_encode(hash('SHA256', $string, true)) . "\n";

Which prints:

    This is the text that I want to hash right here
MD5          : 863d862fcf20fa9eb2252ebc44af1a56
MD5_64_url   : hj2GL88g-p6yJS68RK8aVg~~
SHA1         : 435b78741359972211fe2e967161b5b011e1bb8f
SHA1_64_url  : Q1t4dBNZlyIR_i6WcWG1sBHhu48~
SHA256       : 7f957f328f7d3d653db2ce7301db6813499adbd45b3873a6801500d493813e4e
SHA256_64    : f5V/Mo99PWU9ss5zAdtoE0ma29RbOHOmgBUA1JOBPk4=
SHA256_64_url: f5V_Mo99PWU9ss5zAdtoE0ma29RbOHOmgBUA1JOBPk4~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment