PHP数组加密解密
应用场景:给前台cookie加密
使用环境:tp5
使用方法
以下代码在extend\Lib\Haxi.php
<?php namespace lib; use think\Controller; class Haxi extends Controller{ //加密函数(参数:数组,返回值:字符串) public static $key_t = "sjiofssdsfd";//设置加密种子 public static function encrypt($cookie_array){ $txt = serialize($cookie_array); srand();//生成随机数 $encrypt_key = md5(rand(0,10000));//从0到10000取一个随机数 $ctr = 0; $tmp = ''; for($i = 0;$i < strlen($txt);$i++){ $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]); } return base64_encode(Haxi::key($tmp,Haxi::$key_t)); } //解密函数(参数:字符串,返回值:数组) public static function decrypt($txt){ $txt = Haxi::key(base64_decode($txt), Haxi::$key_t); $tmp = ''; for($i = 0;$i < strlen($txt); $i++) { $md5 = $txt[$i]; $tmp .= $txt[++$i] ^ $md5; } $tmp_t = unserialize($tmp); return $tmp_t; } public static function key($txt,$encrypt_key){ $encrypt_key = md5($encrypt_key); $ctr = 0; $tmp = ''; for($i = 0; $i < strlen($txt); $i++) { $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; $tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; } return $tmp; } }
后台使用
//先引入 use Lib\Haxi;
加密数组$arr ====================
$Haxi = new Haxi();
cookie('shoppinglist', $Haxi->encrypt($arr));
解密数据$_POST['list'] ========================= public function shoppinglist() { $Haxi = new Haxi(); $a = $Haxi->decrypt($_POST['list']); //解密 var_dump($a); }
附上几个其他加密的方式,只不过是字符串https://www.cnblogs.com/liiu/p/10136767.html