php-简单对称加密算法和字符串与十六进制之间的互转函数

 1 <?php
 2 /**
 3 * 简单对称加密算法之加密
 4 * @param String $string 需要加密的字串
 5 * @param String $skey 加密EKY
 6 * @return String
 7 */
 8 function encode($string = '', $skey = 'testphp') {
 9   $skey = str_split(base64_encode($skey));
10   $strArr = str_split(base64_encode($string));
11   $strCount = count($strArr);
12   foreach ($skey as $key => $value) {
13     $key < $strCount && $strArr[$key].=$value;
14   }
15   return str_replace('=', 'O0O0O', join('', $strArr));
16 }
17 
18 /**
19 * 简单对称加密算法之解密
20 * @param String $string 需要解密的字串
21 * @param String $skey 解密KEY
22 * @return String
23 */
24 function decode($string = '', $skey = 'testphp') {
25   $skey = str_split(base64_encode($skey));
26   $strArr = str_split(str_replace('O0O0O', '=', $string), 2);
27   $strCount = count($strArr);
28   foreach ($skey as $key => $value) {
29     $key < $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
30   }
31   return base64_decode(join('', $strArr));
32 }
33 
34 //字符串转换成16进制
35 function str2hex($str, $encoded = 'GBK') {
36   $hex = '';
37   if ($encoded == 'GBK') {
38     $str = mb_convert_encoding($str, 'GBK', 'UTF-8');
39   }
40   for ($i = 0, $length = mb_strlen($str); $i < $length; $i++) {
41     $hex .= dechex(ord($str{$i}));
42   }
43   return $hex;
44 }
45 
46 //16进制转换成字符串
47 function hex2str($hex, $encoded = 'GBK') {
48   $str = '';
49   $arr = str_split($hex, 2);
50   foreach ($arr as $bit) {
51     $str .= chr(hexdec($bit));
52   }
53   if ($encoded == 'GBK') {
54     $str = mb_convert_encoding($str, 'UTF-8', 'GBK');
55   }
56   return $str;
57 }

 

你可能感兴趣的:(对称加密)