1.前言
base编码被用作数据传输编码,通过对字符进行位运算得到key,然后再从”彩虹表”中找到key对应的ascii码来表示编码后的数据,下面来看下其原理介绍。
2.原理

3.PHP的base64编码解码算法实现
<?php
$base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE64BIT = 6;
const BASE64GROUPSIZE = 3;
function base64Encode($str)
{
global $base64Alphabet;
$strLength = strlen($str);
$strIndex = 0;
$encode = '';
while($strLength >= BASE64GROUPSIZE) {
$subStr = substr($str, $strIndex, BASE64GROUPSIZE);
$first = ord($subStr[0]) >> 2;
$second = (ord($subStr[0]) & 3) << 4 | (ord($subStr[1]) & 0xf0) >> 4;
$third = (ord($subStr[1]) & 0xf) << 2 | ord($subStr[2]) >> BASE64BIT;
$fourth = ord($subStr[2]) & 0x3f;
$encode .= $base64Alphabet{$first};
$encode .= $base64Alphabet{$second};
$encode .= $base64Alphabet{$third};
$encode .= $base64Alphabet{$fourth};
$strIndex += BASE64GROUPSIZE;
$strLength -= BASE64GROUPSIZE;
}
if ($strLength % BASE64GROUPSIZE === 0) {
return $encode;
}
$lastStr = substr($str, $strIndex);
$lastFirst = ord($lastStr[0]) >> 2;
$encode .= $base64Alphabet{$lastFirst};
if ($strLength === 1) {
$lastSecond =(ord($lastStr[0]) & 3) << 4;
$encode .= $base64Alphabet{$lastSecond};
$encode .= '==';
} else {
$lastSecond = (ord($lastStr[0]) & 3) << 4 | (ord($lastStr[1]) & 0xf0) >> 4;
$lastThird = (ord($lastStr[1]) & 0xf) << 2;
$encode .= $base64Alphabet{$lastSecond};
$encode .= $base64Alphabet{$lastThird};
$encode .= '=';
}
return $encode;
}
function base64Decode($str)
{
global $base64Alphabet;
$strLength = strlen($str);
$strIndex = 0;
$decode = '';
while($strLength >= BASE64GROUPSIZE + 1) {
$subStr = substr($str, $strIndex, BASE64GROUPSIZE + 1);
$first = strpos($base64Alphabet, $subStr[0]) << 2 | strpos($base64Alphabet, $subStr[1]) >> 4;
$second = (strpos($base64Alphabet, $subStr[1]) & 0xf) << 4 | (strpos($base64Alphabet, $subStr[2]) & 0x3c) >> 2;
$decode .= pack('H*' , dechex($first));
if ($strLength === BASE64GROUPSIZE + 1) {
switch(count(explode('=', $str))) {
case 2:
$decode .= pack('H*' , dechex($second));
case 3:
return $decode;
}
}
$third = (strpos($base64Alphabet, $subStr[2]) & 3) << 6 | strpos($base64Alphabet, $subStr[3]);
$decode .= pack('H*' , dechex($second));
$decode .= pack('H*' , dechex($third));
$strIndex += (BASE64GROUPSIZE + 1);
$strLength -= (BASE64GROUPSIZE + 1);
}
return $decode;
}
$a = 'Hello PHP 你好 PHP!';
var_dump(base64_encode($a), base64_decode(base64_encode($a)));
var_dump(base64Encode($a), base64Decode(base64Encode($a)));
4.运行结果

5.参考
https://datatracker.ietf.org/doc/rfc4648/如无特殊说明,文章均为本站原创,转载请注明出处。如发现有什么不对的地方,希望得到您的指点。