<?php

	//////////////////////////////////////////////////////////////////////////
	//									//
	//   Rafael Páez - @fikih888  						//
	//   Caesar Cipher for hexadecimal					//
	//   Script that uses Caesar cipher to encrypt/decrypt a message	//
	//   using a personalised dictionary					//
	//									//
	//////////////////////////////////////////////////////////////////////////


	// This function encrypts a message "str" using only the characters in "dict" with a shift indicated in "shift"
	function encrypt_msg($dict,$str,$shift)
	{
		$new_str="";
		$total=count($dict);
		$strlen=strlen($str);
		for($i=0;$i<$strlen;$i++)
		{
			$char=substr($str,$i,1);
			$index=array_search($char,$dict);
			$new_index=($index + $shift) % $total;
			$new_str="$new_str"."$dict[$new_index]";
		}

		return $new_str;
	}

	// This function decrypts a message "str" using only the characters in "dict" with a shift indicated in "shift"
	function decrypt_msg($dict,$str,$shift)
	{
		$new_str="";
		$total=count($dict);
		$strlen=strlen($str);
		for($i=0;$i<$strlen;$i++)
		{
			$char=substr($str,$i,1);
			$index=array_search($char,$dict);
			$new_index=($index - $shift) % $total;
			if($new_index<0)
			{
				$new_index=$new_index + $total;
			}
			$new_str="$new_str"."$dict[$new_index]";
		}

		return $new_str;
	}


	////////////////////
	// Example

	$dict=array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); // Dictionary
	$str="0123456789abcdef"; // Message to encrypt/decrypt
	$shift=3 // Shift used;

	// Encrypt a message
	$str_encrypted=encrypt_msg($dict, $str, $shift);

	// Decrypt a message
	$str_decrypted=decrypt_msg($dict, $str, $shift1);

	// Print results
	echo "original str: $str<br />";
	echo "shift: $shift<br /><br />";
	echo "encrypted str: $str_encrypted<br /><br />";
	echo "decrypted str: $str_decrypted<br /><br />";


?>