【问题标题】:Base 64 hash to make URL shorterBase 64 哈希使 URL 更短
【发布时间】:2011-06-09 07:32:31
【问题描述】:

PHP 的 sha256 输出一个长度为 64 个字符的字符串,因为它是以 16 为底的。 如何将其转换为 base 64 以减少其长度?

【问题讨论】:

标签: php hash base64 hex


【解决方案1】:
base64_encode(hash('sha256', 'hello', true));

【讨论】:

  • 长度从 64 个字符减少到 44 个字符
  • PHP 的 base64_encode() 不是 url 安全的。使用包装器来解决这个问题:function urlsafe_b64encode($string) { $data = base64_encode($string); $data = str_replace(array('+','/','='),array('-','_',''),$data); return $data; }
  • @user703016 好的,我想知道编码后的值是否可以解码? base64_encode(hash('sha256', 'hello', true));??
【解决方案2】:

如果您已经拥有哈希并且无法控制它的生成,那么应该可以使用以下方法:

<?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");


?>

返回:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

将散列的大小从 64 减少到 44。

【讨论】:

    【解决方案3】:

    要在碱基之间进行转换,请使用http://php.net/manual/en/function.base-convert.php

    按照上面的答案去,这对这里的评论不起作用。

    【讨论】:

    • base_convert 不接受 64 作为基础。它最多只能接受 36 个。
    • 点了,更新了答案,以便其他人可以从我的错误中吸取教训
    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多