一、Base64编码原理
步骤1:将所有字符转化为ASCII码;
步骤2:将ASCII码转化为8位二进制;
步骤3:将二进制分组,每组6位, 组数需3的倍数,否则后面补全是0的组;
步骤4:将每组6位二进制前补两个0凑足8位,再转为十进制;
步骤5:从Base64编码表获取十进制对应的Base64编码;
说明:不足补0的最终Base64编码为=,而不是A
二、Base64编码示例
示例一:zyq对应Base64编码为enlx
示例二:mzwu对应Base64编码为bXp3dQ==
例二中, 被编码字符长度不是3的倍数,后面都用0代替,对应的输出字符为=
/** * 编码 * * @param string $string * @return */ function b64encode($string = '') { $binval = convertToBinary($string); $final = ""; $start = 0; while ($start < strlen($binval)) { if (strlen(substr($binval, $start)) < 6) $binval .= str_repeat("0", 6 - strlen(substr($binval, $start))); $tmp = bindec(substr($binval, $start, 6)); if ($tmp < 26) $final .= chr($tmp + 65); elseif ($tmp > 25 && $tmp < 52) $final .= chr($tmp + 71); elseif ($tmp == 62) $final .= "+"; elseif ($tmp == 63) $final .= "/"; elseif (!$tmp) $final .= "A"; else $final .= chr($tmp - 4); $start += 6; } if (strlen($final) % 4 > 0) $final .= str_repeat("=", 4 - strlen($final) % 4); return $final; } /** * 转成二进制 * * @param mixed $string * @return */ function convertToBinary($string) { if (strlen($string) <= 0) return; $tmp = decbin(ord($string[0])); $tmp = str_repeat("0", 8 - strlen($tmp)) . $tmp; return $tmp . convertToBinary(substr($string, 1)); } /** * 解码 * * @param mixed $str * @return */ function b64decode($str) { $B64List = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; $len = strlen($str); if ($len % 4 != 0) return ''; $res = $bins = ''; for ($i = 0; $i < $len; $i++) { $nChar = substr($str, $i, 1); if ($nChar == '=') break; $oldValue = strpos($B64List, $nChar); $binValue = substr('000000' . decbin($oldValue), -6); $bins .= $binValue; if (strlen($bins) >= 8) { $deChar = substr($bins, 0, 8); $bins = substr($bins, 8); $res .= chr(bindec($deChar)); } } return $res; }