<?php
/**字符串加解密
 */
class LibEncry
{
    private $arr_encry_hash = array();
    private $encry_hash_len = 0;
    private $encryKey = 3090712;
    function __construct(){
        $this->arr_encry_hash = array(
        3121344,
        5346,
        32,
        5768,
        345,
        3434,
        4563,
        895345,
        45345,
        8945345,
        453345,
        4895345,
        34535,
        8945,
        389354,
        3489535,
        34543445
        );
        $this->encry_hash_len = count($this->arr_encry_hash);
    }
	
	/**获取加密键
     * @param $str [string] :待加密的字符串
     * @param $key [int] :密钥
     * @return  [string] :
     */
	public function getEncryKey($str)
	{
		if($str==''){
		   throw new  Exception ('getEncryKey Error');
		}
		$len = strlen($str);
		$hash = array(2345188973,4524123849,9862334734,8293453740,1802989344,4358993899,6934839434,3230932044);
		$hash_len = count($hash);
		$hash_value = $hash[ ( ord($str[0]) + ord($str[$len-1]) ) % $hash_len];
		$key = $hash_value;
		for($i=0;$i<$len;$i++){
			$c = ord($str[$i]);
			$key = $key ^ ($c * $i * 1000000);
		}
		return abs($key);
	}

    /**解密字符串
     * @param $str [string] :待加密的字符串
     * @param $key [int] :密钥
     * @return  [string] :
     */
	public function encode($str,$key = 3090712)
	{
		$this->encryKey = $key;
        $str = base64_encode($str);
        $len = strlen($str);
        $bin = @pack("a{$len}", $str);
        $bin_len = strlen($bin);
        $result = '';
        for($i=0;$i<$bin_len;$i+=4){
           $buffer = substr($bin,$i,4);
           $result .= $buffer ^ @pack('l2',$this->encryKey + $this->arr_encry_hash[$i % $this->encry_hash_len],0);
        }
        return base64_encode($result);
    }

    /**解密字符串
     * @param $bin [bin] :待解密的二进制
     * @param $key [int] :密钥
     * @return  [string] :
     */
	public function decode($bin,$key = 3090712){
		$this->encryKey = $key;
		$bin = base64_decode($bin);
        $bin_len = strlen($bin);
        $result = '';
        for($i=0;$i<$bin_len;$i+=4){
           $buffer = substr($bin,$i,4);
           $result .= $buffer ^ @pack('l2',$this->encryKey + $this->arr_encry_hash[$i % $this->encry_hash_len],0);
        }
        $result = base64_decode($result);
        return $result;
    }
}
