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

  • 相关阅读:
    SendInput模拟键盘输入的问题 <转>
    tinyMce3.21 使用随笔
    ORM的一些思考
    VS2008 , 1330 , 数字签名错误.
    .Net Reflector 工具 过期后使用小工具。
    就当是一个新的设计模式!
    OpenSUSE 11 下 Mono 2 开发笔记。
    转:)CNBlogs引用第三方组(控)件明细^_^
    DBLinq ,没实现 Log !
    DotNet 的一些知识点
  • 原文地址:https://www.cnblogs.com/chenliuxiao/p/12482095.html
Copyright © 2011-2022 走看看