【转】php字符串加密解密

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: yl
 5  * Date: 2018/9/27
 6  * Time: 13:50
 7  */
 8 
 9 class Encryption
10 {
11     /*********************************************************************
12     函数名称:encrypt
13     函数作用:加密解密字符串
14     使用方法:
15     加密   :encrypt('str','E','nowamagic');
16     解密   :encrypt('被加密过的字符串','D','nowamagic');
17     参数说明:
18     $string  :需要加密解密的字符串
19     $operation:判断是加密还是解密:E:加密  D:解密
20     $key   :加密的钥匙(密匙);
21 
22     http://www.cnblogs.com/roucheng/
23      *********************************************************************/
24     public function encrypt($string,$operation,$key='')
25     {
26         $key=md5($key);
27         $key_length=strlen($key);
28         $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
29         $string_length=strlen($string);
30         $rndkey=$box=array();
31         $result='';
32         for($i=0;$i<=255;$i++)
33         {
34             $rndkey[$i]=ord($key[$i%$key_length]);
35             $box[$i]=$i;
36         }
37         for($j=$i=0;$i<256;$i++)
38         {
39             $j=($j+$box[$i]+$rndkey[$i])%256;
40             $tmp=$box[$i];
41             $box[$i]=$box[$j];
42             $box[$j]=$tmp;
43         }
44         for($a=$j=$i=0;$i<$string_length;$i++)
45         {
46             $a=($a+1)%256;
47             $j=($j+$box[$a])%256;
48             $tmp=$box[$a];
49             $box[$a]=$box[$j];
50             $box[$j]=$tmp;
51             $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
52         }
53         if($operation=='D')
54         {
55             if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
56             {
57                 return substr($result,8);
58             }
59             else
60             {
61                 return'';
62             }
63         }
64         else
65         {
66             return str_replace('=','',base64_encode($result));
67         }
68     }
69 }
70 
71 ?>