• 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

  • 相关阅读:
    python模块之sys与os
    Python模块之time、datetime
    一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10
    js闭包
    js删除局部变量
    数据库 事务
    jQuery全屏滚动插件fullPage.js
    jdk环境变量
    MyEclipse优化设置(最详细版本)
    oracle查询性能优化
  • 原文地址:https://www.cnblogs.com/chenliuxiao/p/12482095.html
Copyright © 2020-2023  润新知