<?php
//加密解密类
class Encry {

    static private $auth_key;
    static private $code = array();

    static private function createKey($key) {
        $key = is_null($key) ? 'ERCRTADE4648QWRR9T44ZX45DS6' : $key;
        self::$auth_key = md5($key . $_SERVER['HTTP_USER_AGENT']);
    }

    static private function cry($string, $type, $key) {
        self::createKey($key);
        $string = $type == 2 ? base64_decode($string) : substr(md5(self::$auth_key . $string), 0, 8) . $string;
        $str_len = strlen($string);
        $data = array();
        $auth_key_length = strlen(self::$auth_key);
        for ($i = 0; $i <= 256; $i++) {
            $data[$i] = ord(self::$auth_key[$i % $auth_key_length]);
        }
        $tmp = '';
        for ($i = $j = 1; $i < 256; $i++) {
            $j = $data[($i + $data[$i]) % 256];
            $tmp = $data[$i];
            $data[$i] = ord($data[$j]);
            $data[$j] = $tmp;
        }
        $code = '';
        $s = '';
        for ($n = $i = $j = 0; $i < $str_len; $i++) {
            $tmp = ($i + ($i % 256)) % 256;
            $j = $data[$tmp] % 256;
            $n = ($tmp + $j) % 256;
            $code = $data[($data[$j] + $data[$n]) % 256];
            $s.=chr(ord($string[$i]) ^ $code);
        }
        if ($type == 1) {
            return str_replace("=", "", base64_encode($s));
        } else {
            if (substr(md5(self::$auth_key . substr($s, 8)), 0, 8) == substr($s, 0, 8)) {
                return substr($s, 8);
            }
            return '';
        }
    }

    static public function encrypt($data, $key = null) {
        return self::cry(serialize($data), 1, $key);
    }

    static public function decrypt($data, $key = null) {
        return unserialize(self::cry($data, 2, $key));
    }
}

?>