SecurityKey.class.php 1.51 KB
<?php
class Util_Utils_SecurityKey
{	
	
	/**
	 * 加密
	 * 
	 * @param string $value
	 * @param string $privacyKey
	 * @return string |false
	 */
	public static function encrypt($value, $privacyKey = '')  
	{  
	    if(empty($privacyKey))
	    {
	        return false ;
	    }
		srand((double)microtime()*1000000);  
		$encryptKey = md5(rand(0,32000));
		$ctr = 0;  
		$tmp = "";  
		for ($i=0;$i<strlen($value);$i++)  
		{  
			if ($ctr==strlen($encryptKey)) $ctr=0;  
			$tmp.= substr($encryptKey,$ctr,1) . (substr($value,$i,1) ^ substr($encryptKey,$ctr,1)); 
			$ctr++;  
		}  
		return SecurityKey::keyED($tmp, $privacyKey);  
	}  
	
	/**
	 * 解密
	 * 
	 * @param string $value
	 * @param string $privacyKey
	 * @return string|false
	 */
	public static function decrypt($value, $privacyKey = '')  
	{  
		if(empty($privacyKey))
	    {
	       return false;
	    }
		$value = SecurityKey::keyED($value, $privacyKey);
		$tmp = '';  
		for ($i=0;$i<strlen($value);$i++)  
		{  
			$md5 = substr($value,$i,1); 
			$i++;  
			$tmp.= (substr($value,$i,1) ^ $md5);  
		}  
		return $tmp;  
	}  
	
	/**
	 * 密钥加解密
	 * 
	 * @param string $value
	 * @param string $encryptKey
	 * @return string
	 */
	public static function keyED($value, $encryptKey)  
	{  
		$encryptKey = md5($encryptKey);  
		$ctr = 0;  
		$tmp = '';  
		for ($i=0;$i<strlen($value);$i++)  
		{  
			if ($ctr == strlen($encryptKey)) 
			{
				$ctr = 0; 	
			} 
			$tmp.= substr($value,$i,1) ^ substr($encryptKey,$ctr,1);  
			$ctr++;  
		}  
		return $tmp;  
	}  

}