hidarikani
hidarikani

Reputation: 1131

Base 64 hash to make URL shorter

PHP's sha256 outputs a string which is 64 chars long because it's base 16. How can I convert it to base 64 to reduce its length?

Upvotes: 1

Views: 4783

Answers (3)

MGwynne
MGwynne

Reputation: 3522

If you already have the hash and aren't in control of it's generation, then something like the following should work:

<?php

function hex2char($c) {
  return chr(hexdec($c));
}

function char2hex($c) {
  return str_pad(dechex(ord($c)),2,"0",STR_PAD_LEFT);
}


function base16to64($v) {
  return base64_encode(implode(array_map("hex2char", str_split($v,2))));

}

function base64to16($v) {
  return implode(array_map("char2hex",str_split(base64_decode($v),1)));

}


$input = hash('sha256', 'hello');

print($input . "\n");
print(base16to64($input) . "\n");
print(base64to16(base16to64($input)) . "\n");


?>

returning:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

reducing the size of the hash from 64 to 44.

Upvotes: 3

Ben G
Ben G

Reputation: 26771

To convert between bases use http://php.net/manual/en/function.base-convert.php

Go with the above answer, this doesn't work per the comment here.

Upvotes: 0

user703016
user703016

Reputation: 37945

base64_encode(hash('sha256', 'hello', true));

Upvotes: 9

Related Questions