應用場景:給前台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