php 可加密解密64编码解码,用于对ID的编码解码

投稿作者:热心网友 围观人数:54 所属分类:好玩的网页代码

php 可加密解密64编码解码,用于对ID的编码解码,如?id=123123可加密表示成?id=dhr_U

<?php

/**
 * 可加密64编码解码,用于对ID的编码解码
 */
class code {

    private $key = null;

    function __construct($key) {
        $this->key = $key;
    }

    /**
     * 对数字编码
     */
    function encode($value) {
        $x = sprintf("%d", intval($value) ^ intval($this->key));
        $y = $this->encode_b64(intval($x));
        return $y;
    }

    /**
     *解码
     */
    function decode($pwd) {
        $pwd = $this->decode_b64($pwd);
        $re = strval(intval($pwd) ^ intval($this->key));
        return $re;
    }

    /**
     * 重置密钥
     */
    function reset_key($key) {
        $this->key = $key;
    }

    /**
     * 64进位编码
     */
    public function encode_b64($n) {
        $table = ''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'';
        $result = array();
        $temp = $n;
        if (0 == $temp) {
            $result[] = ''0'';
        } else {
            while (0 < $temp) {
                $result[] = $table[$temp % 64];
                $temp = intval($temp / 64);
            }
        }
        //反转数组
        krsort($result);
        return implode('''', $result);
    }

    /**
     * 64进位解码
     */
    public function decode_b64($str) {
        $table = array("0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5,
            "6" => 6, "7" => 7, "8" => 8, "9" => 9,
            "a" => 10, "b" => 11, "c" => 12, "d" => 13, "e" => 14, "f" => 15, "g" => 16,
            "h" => 17, "i" => 18, "j" => 19, "k" => 20, "l" => 21, "m" => 22, "n" => 23,
            "o" => 24, "p" => 25, "q" => 26, "r" => 27, "s" => 28, "t" => 29, "u" => 30,
            "v" => 31, "w" => 32, "x" => 33, "y" => 34, "z" => 35,
            "A" => 36, "B" => 37, "C" => 38, "D" => 39, "E" => 40, "F" => 41, "G" => 42,
            "H" => 43, "I" => 44, "J" => 45, "K" => 46, "L" => 47, "M" => 48, "N" => 49,
            "O" => 50, "P" => 51, "Q" => 52, "R" => 53, "S" => 54, "T" => 55, "U" => 56,
            "V" => 57, "W" => 58, "X" => 59, "Y" => 60, "Z" => 61,
            "-" => 62, "_" => 63);
        $result = 0;
        foreach (range(0, strlen($str) - 1) as $i) {
            $result *= 64;
            $result += $table[$str[$i]];
        }
        return $result;
    }

}

$d = new code(''123123'');
echo $d->encode(222584587), "\\n";
echo $d->decode(''dhr_U''), "\\n";

$d = new code(''333333'');
echo $d->encode(222584587), "\\n";
echo $d->decode(''dgkAu''), "\\n";



the end
免责声明:本文来自鸿哥资源网发布,但不代表本站的观点和立场。
已有次赞
我要评论 0条评论,0条回复
请先登录后再评论

登录您的账号