<?
/**
*	CRYPTOGRAPHY CLASS
*
*	Simple KeyPhrase cryptography class. 
*	It allows to encrypt and decrypt a string based on a keyPhrase.
*	Based on the (TEA) Tiny Encrypion Algorythm.
*	
* @link http://framework.doutromundo.com/
* @version 0.4.0
* @copyright Copyright: 2002-2005 Doutromundo
* @author Gregory Brown <bugzbrown@gmail.com>
* @access public
* @package Core
*/
class crypto{

	/**
	* The key phrase to use (note the longer the phrase the more secure it will be)
	*@var string;
	*/
    var $keyPhrase="";
	/**
	* The string to be encrypted/decrypted
	*@var string;
	*/
    var $input="";
	/**
	* The encrypted/decrypted string.
	*@var string;
	*/
    var $output="";
	
	/**
	*@desc Core of the function - responsible for generating the hash
	*@access Private
	*@return String
	*@param String $txt : String to encrypt
	*@param String $encrypt_key : The encryption key
	*/

	function encryption_keyer($txt,$encrypt_key){
		$ctr=0;
		$tmp = "";
		$txt_len=strlen($txt);
		for ($i=0;$i<$txt_len;$i++)
		{
			if ($ctr==strlen($encrypt_key)) $ctr=0;
			$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
			$ctr++;
		}
		return $tmp;
	}
	
	/**
	* Get input string and keyphrase and encrypt the string sending it to $output
	* @return void
	* @access Public
	*/
	function encrypt_string(){
		$txt = $this->input;
		$key = $this->keyPhrase;
		
		srand((double)microtime()*1000000);
		$encrypt_key = md5(rand(0,32000));
		$ctr = 0;
		$tmp = "";
		$txt_len = strlen($txt);
		for ($i=0;$i < $txt_len;$i++)
		{
			if ($ctr==strlen($encrypt_key)) $ctr=0;
			$tmp.= substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
			$ctr++;
		}
		$hash= $this->encryption_keyer($tmp,$key);
		$hashLen = strlen($hash);
		$hexa = "";
		for ($j=0;$j < $hashLen;$j++){
			$tmpH =  base_convert((ord(substr($hash,$j,1))), 10, 16);
			$hexa .= strlen($tmpH)<2?"0$tmpH":"$tmpH";
		}
		$this->output = $hexa;
	}
	
	/**
	*Get input string and keyphrase and decrypt the string sending it to output
	* @return void
	* @access Public
	*/
	function decrypt_string(){
		$txt = $this->input;
		$key = $this->keyPhrase;

		$hexaLen = strlen($txt);
		$hash = "";
		for ($j=0;$j < $hexaLen;$j++){
	
			$tmpHex =  substr($txt,$j,2);
			$tempOrd = base_convert($tmpHex,16,10);
			$hash .=chr($tempOrd);
			$j++;
		}
		$hashd= $this->encryption_keyer($hash,$key);
		
		$tmp = "";
		$txt_len=strlen($hashd);
		for ($i=0;$i<$txt_len;$i++)
		{
			$md5 = substr($hashd,$i,1);
			$i++;
			$tmp.= (substr($hashd,$i,1) ^ $md5); 
		}
		$this->output = $tmp;
	}
}


/*   EXEMPLO DE UTILIZACAO */
$k =new crypto();
$k->keyPhrase = "a frase que deve ser utilizada do outro lado para decodificar a string"; 
$k->input = "Essa e a string que sera codificada";
$k->encrypt_string();
$fraseCodificada = $k->output;

// bom com esse exemplo ja deu pra perceber como funciona ne? 
// pra descodificar - basta usar o decrypt_string();

?>