一个简易的php加密类

转:php5应用实例详解:使用zend framework 与smarty构筑真正的MVC模式应用

<?php
	/*  一个简易的加密类(可逆)
	 *  静态调用,不需实例化Crypt类	
	 */
	class Crypt{
		/**
		 *基础加密,结合passport_key与key密钥做加密
		 *@param txt : 明文待加密
		 *@param key :密钥
		 *@return    : 加密后的字符串 
		 */
		public static function passport_encrypt($txt,$key){
			$encrypt_key = md5(rand(0,32000));
			$ctr = 0;
			$tmp = '';
			for($i = 0;$i<strlen($txt);$i++){
				$ctr  = ($ctr == strlen($encrypt_key) ?0:$ctr);
				$tmp .=  $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
			}
 
			return base64_encode(Crypt::passport_key($tmp,$key));
		}
 
		public static function passport_key($txt,$encrypt_key){
			$encrypt_key = md5($encrypt_key);
			$ctr = 0;
			$tmp = '';
			for($i = 0;$i < strlen($txt);$i++){
				$ctr  = ($ctr == strlen($encrypt_key) ?0:$ctr);
				$tmp .= $txt[$i]^$encrypt_key[$ctr++];
			}
			return $tmp;
		}
		/**
		 *解密,剥离密钥
		 *@param txt : 待解密密文
		 *@param key :密钥
		 *@return    : 解密后的字符串 
		 */
		public static function passport_decrypt($txt,$key){
			$txt = Crypt::passport_key(base64_decode($txt),$key);
			$tmp = '';
			for($i = 0;$i<strlen($txt);$i++){
				$md5 = $txt[$i];
				$tmp.= $txt[++$i] ^ $md5;
			}
			return $tmp;
		}
 
	}
 
	$txt = "I will be backI";
	$key = "justfortest";
	$encrypt = Crypt::passport_encrypt($txt,$key);
	$decrypt = Crypt::passport_decrypt($encrypt,$key);
	echo "from   	:$txt <br/>";
	echo "key    	:$key <br/>";
	echo "encrypt	:$encrypt <br/>";
	echo "decrypt	:$decrypt <br/>";

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注