任意进制转换,只要把字典字符集填充够长,顺序打乱,配合 mb_ord() 可实现逐字加密。
function baseConvert($num,$fromBase=10,$toBase=95) { if ($fromBase!=10){ $num=baseConvertReverse($num.'',$fromBase,10)*1; } $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"#%&$\')*(,-+./:<=>;?@[\]^_}`|{~"; $result = ''; while(1) { $remainder = $num % $toBase; $result = $chars[$remainder] . $result; $num = intdiv($num, $toBase); if($num==0){break;} } return $result; } function baseConvertReverse($str, $fromBase=95, $toBase=10) { $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"#%&$\')*(,-+./:<=>;?@[\]^_}`|{~"; $len = strlen($str); $num = 0; for($i=0;$i<$len;$i++) { $pos = strpos($chars,$str[$i]); $num = $num * $fromBase + $pos; } if ($toBase!=10){ $num=baseConvert($num,10,$toBase); } return $num; } // 任意进制 function superBaseConvert($code,$fromBase=10,$toBase=95) { $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"#%&$\')*(,-+./:<=>;?@[\]^_}`|{~"; $code=$code.''; // 从N进制转为十进制 if ($fromBase!=10){ $len = strlen($code); $dec = 0; for($i=0;$i<$len;$i++) { $pos = strpos($chars,$code[$i]); $dec = $dec * $fromBase + $pos; } }else{ $dec=$code; } // 从十进制转为N进制 if ($toBase==10){ return $dec; } $result = ''; while(true) { $remainder = $dec % $toBase; $result = $chars[$remainder] . $result; $dec = intdiv($dec, $toBase); if($dec==0){break;} } return $result; }