<?php
/**
 * @version $Id: passport.func.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

/**
	* Passport 加密函数
	*
	* @param		string		等待加密的原字串
	* @param		string		私有密匙(用于解密和加密)
	*
	* @return	string		原字串经过私有密匙加密后的结果
	*/
function passport_encrypt($txt, $key)
{
	srand((double)microtime() * 1000000);
	$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(passport_key($tmp, $key));
}

/**
* Passport 解密函数
*
* @param		string		加密后的字串
* @param		string		私有密匙(用于解密和加密)
*
* @return	string		字串经过私有密匙解密后的结果
*/
function passport_decrypt($txt, $key)
{
	$txt = passport_key(base64_decode($txt), $key);
	$tmp = '';
	for ($i = 0; $i < strlen($txt); $i++)
	{
		$tmp .= $txt[$i] ^ $txt[++$i];
	}
	return $tmp;
}

/**
* Passport 密匙处理函数
*
* @param		string		待加密或待解密的字串
* @param		string		私有密匙(用于解密和加密)
*
* @return	string		处理后的密匙
*/
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;
}

/**
* Passport 信息(数组)编码函数
*
* @param array 待编码的数组
*
* @return string 数组经编码后的字串
*/
function passport_encode($array)
{
	$arrayenc = array();
	foreach($array as $key => $val)
	{
		$arrayenc[] = $key.'='.urlencode($val);
	}
	return implode('&', $arrayenc);
}

/**
 * phpwind
 */
function StrCode($string,$action='ENCODE')
{
	global $pb_sitehash;
	$key	=substr(md5($_SERVER['HTTP_USER_AGENT'].$pb_sitehash),8,18);
	$string	=$action == 'ENCODE' ? $string : base64_decode($string);
	$len	=strlen($key);
	$code	='';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : base64_encode($code);
	return $code;
}

?>