开发者

Base 64 hash to make URL shorter

PHP's sha256 outputs a string whi开发者_运维知识库ch is 64 chars long because it's base 16. How can I convert it to base 64 to reduce its length?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜