由于在加密解密的过程中,加密的串是乱码的,以是加乱码的串进行了base64编码或者转为16进制
同理解密的过程恰好相反,详细方法如下:
//AES加密
function mc_encrypt($data, $mc_key,$method = 'AES-256-ECB',$basecode=\"大众base64\公众,$iv=\"大众\"大众) { $options = OPENSSL_RAW_DATA; //数据格式选项(可选) $encode = openssl_encrypt($data, $method, $mc_key, $options,$iv); if($basecode == \"大众hex\"大众){ //hex加密 $encode = String2Hex($encode); }else{ //base64加密 $encode = base64_encode($encode); } return $encode;}
//AES解密
function mc_decrypt($result, $mc_key,$method = 'AES-256-ECB',$basecode=\"大众base64\"大众,$iv=\公众\公众) { $options = OPENSSL_RAW_DATA; //数据格式选项(可选) if($basecode == \"大众hex\"大众){ //hex解密 $result = Hex2String($result); }else{ //base64解密 $result = base64_decode($result); } $decrypted = openssl_decrypt($result, $method, $mc_key, $options,$iv); return $decrypted;}
//16进制串转为字符串
function Hex2String($hex) { $string = ''; for ($i = 0; $i < strlen($hex) - 1; $i+=2) { $string .= chr(hexdec($hex[$i] . $hex[$i + 1])); } return $string;}
//字符串转为16进制串
function String2Hex($string) { $hex = ''; for ($i = 0; $i < strlen($string); $i++) { $tmp = dechex(ord($string[$i])); if (strlen($tmp) == 1) { $tmp = \"大众0\"大众 . $tmp; } $hex .= $tmp; } return $hex;}