余生's Blog
余生's Blog
正在加载一言...
PHP自定义密文加密解密类
作者: 余生    时间: 2020-06-25    分类: 网站源码

感觉日后还会用到,先记一下

<?php

// +----------------------------------------------------------------------
// | Hidove [ www.hidove.cn ]
// +----------------------------------------------------------------------
// | Author: Ivey <loliconla@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020年4月9日15:09:28
// +----------------------------------------------------------------------


namespace app\common\util;
/**
 * Class HidoveNumberEncode PHP自定义密文加密解密类
 * @package app\common\util
 */
class HidoveNumberEncode
{
    private $encodeStr, $key, $length, $codelen, $codenums, $codeext;

    // 初始化
    public function __construct($length = 9, $encodeStr = 'Flpvf70CsakVjqgeWUPXQxSyJizmNH6B1u3b8cAEKwTd54nRtZOMDhoG2YLrI', $key = 2543.5415412812)
    {
        $this->key = $key;
        $this->length = $length;
        $this->encodeStr = $encodeStr;
        $this->codelen = substr($this->encodeStr, 0, $this->length);
        $this->codenums = substr($this->encodeStr, $this->length, 10);
        $this->codeext = substr($this->encodeStr, $this->length + 10);
    }

    // 编码
    public function encode($nums)
    {
        $rtn = "";
        $numslen = strlen($nums);
        //密文第一位标记数字的长度
        $begin = substr($this->codelen, $numslen - 1, 1);
        //密文的扩展位
        $extlen = $this->length - $numslen - 1;
        $temp = str_replace('.', '', $nums / $this->key);
        $temp = substr($temp, -$extlen);
        $arrextTemp = str_split($this->codeext);
        $arrext = str_split($temp);
        foreach ($arrext as $v) {
            $rtn .= $arrextTemp[$v];
        }
        $arrnumsTemp = str_split($this->codenums);
        $arrnums = str_split($nums);
        foreach ($arrnums as $v) {
            $rtn .= $arrnumsTemp[$v];
        }
        return $begin . $rtn;
    }

    //解码
    public function decode($code)
    {
        $begin = substr($code, 0, 1);
        $rtn = '';
        $len = strpos($this->codelen, $begin);
        if ($len !== false) {
            $len++;
            $arrnums = str_split(substr($code, -$len));
            foreach ($arrnums as $v) {
                $rtn .= strpos($this->codenums, $v);
            }
        }

        return $rtn;
    }
}

添加新评论

最热文章