在线文档教程

php json 数据加密解密

<?php
namespace app\shuju\model;
class DataSecurityTool
{

    /**
     * 加密函数
     * @param [type] $context [description]
     * @return [type] [description]
     */
    public function opEncryption($context,$key_main = "this is main key", $key_sub = "this is sub key")
    {
        $key_main = str_split($key_main);
        $key_sub = str_split($key_sub);
        $context_bytes = str_split($context);
        $context_len = count($context_bytes);
        $cur_key_len = count($key_main);
        if (empty($context_bytes)) {
            return null;
        }
        $context_encrypted = [];
        for ($i = 0; $i < $context_len; $i++) {
            $context_encrypted[$i] = ord($context_bytes[$i] ^ $key_main[$i % $cur_key_len]);
        }
        $cur_key_len = count($key_sub);
        for ($i = 0; $i < $context_len; $i++) {
            $context_encrypted[$i] = $context_encrypted[$i] ^ ord($key_sub[$i % $cur_key_len]);
        }
        $data = array_map(function ($v) {
            return chr($v);
        }, $context_encrypted);
        return base64_encode(implode($data));
    }
    /**
     * 解密函数
     * @param [type] $context [description]
     * @return [type] [description]
     */
    public function opDecryption($context,$key_main = "this is main key", $key_sub = "this is sub key")
    {
        $key_main = str_split($key_main);
        $key_sub = str_split($key_sub);
        $context = base64_decode($context);
        $context_bytes = str_split($context);
        $context_len = count($context_bytes);
        $cur_key_len = count($key_sub);
        if (empty($context_bytes)) {
            return null;
        }
        $context_encrypted = [];
        for ($i = 0; $i < $context_len; $i++) {
            $context_encrypted[$i] = ord($context_bytes[$i] ^ $key_sub[$i % $cur_key_len]);
        }
        $cur_key_len = count($key_main);
        for ($i = 0; $i < $context_len; $i++) {
            $context_encrypted[$i] = $context_encrypted[$i] ^ ord($key_main[$i % $cur_key_len]);
        }
        $data = array_map(function ($char) {
            return chr($char);
        }, $context_encrypted);
        return implode("", $data);
    }
}
// //data for encrypt
// $info = ["access_token" => "as2009_12_34", "name" => "我的", "age" => 25, "sex" => "male"];
// $json_data = json_encode($info, JSON_UNESCAPED_UNICODE);
// $dataSec = new DataSecurityTool();
// //encrypt
// $encry_data = $dataSec->opEncryption($json_data);
// echo $encry_data;
// //decrypt
// $decry_data = $dataSec->opDecryption($encry_data);
// echo $decry_data;