zoukankan      html  css  js  c++  java
  • PHP数组加密解密

    应用场景:给前台cookie加密

    使用环境:tp5

    使用方法

    以下代码在extendLibHaxi.php

    <?php
    namespace lib;
    
    use thinkController;
    
    
    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 LibHaxi;

    加密数组$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

  • 相关阅读:
    awk-使用
    缓存使用
    一致性hash-java实现treemap版
    线程同步-CountDownLatch
    一致性hash算法
    linux-配置字符串-grep
    linux-查找命令-find
    linux-网络监控命令-netstat进阶
    linux-网络监控命令-netstat初级
    linux-单引号、双引号、反引号的区别。
  • 原文地址:https://www.cnblogs.com/chenliuxiao/p/12482095.html
Copyright © 2011-2022 走看看