Ancient Cryptography-ciphars
Ancient cryptography-ciphars
1.caesar ciphars-In cryptography caesar ciphar are also known as shift ciphers, caesar's ciphar etc.. this technique of encryption is thousands of years old.In this technique we shift a character with shift value, suppose we have a character class[a-z](means a to z characters) that is situated from 0 to 25.
now with a shift value i shift a position of character.like i have a message 'hs' .
with shift 5. this message will become 'mx'. thus we encrypt a message by caesar ciphars. this is very weak technique of encryption. because there is 25 values that you can give to shift.
although you do not know the value of shift, you can break the encryptoin by knowing the occurance frequencies of particular characters.
alogrithm seen in picture is used by caesar ciphars
now lets make a little application that work on casear ciphars alogrithm in PHP--
first make a array of 26 element containig a to z characters as element and element values as characters general position.
like-- $alpha=array('a'=>'1','b'=>'2','c'=>'3','d'=>'4','e'=>'5','f'=>'6','g'=>'7','h'=>'8','i'=>'9','j'=>'10','k'=>'11','l'=>'12','m'=>'13','n'=>'14','o'=>'15','p'=>'16','q'=>'17','r'=>'18','s'=>'19','t'=>'20','u'=>'21','v'=>'22','w'=>'23','x'=>'24','y'=>'25','z'=>'26');
Now i will make a function with name cipher containing two argument first argument as string to be encryption and second argument as shift value.
further making of this function you reader should be learned all the essencial in built functions on array in php.
like array_flip(), array_reverse(), is_array(). and some little about mini programming language called regexps(ragular expressions ). In php there is in built functions for regexps support.
//function for shift cipher
function cipher($str, $shift)
{
$string=strtolower($str);
if(is_array($string)==true)
{
throw new Exception("Can't use array as string");
}
if($shift>0)
{
$alpha=array('a'=>'1','b'=>'2','c'=>'3','d'=>'4','e'=>'5','f'=>'6','g'=>'7','h'=>'8','i'=>'9','j'=>'10','k'=>'11','l'=>'12','m'=>'13','n'=>'14','o'=>'15','p'=>'16','q'=>'17','r'=>'18','s'=>'19','t'=>'20','u'=>'21','v'=>'22','w'=>'23','x'=>'24','y'=>'25','z'=>'26');
$alpha_num=array_keys($alpha);
$match_num=array();
$nums=array_flip($alpha);
$encoded=array();
if($shift>26)
{
$shift=$shift%26;
}
for ($i=0; $i < strlen($string) ; $i++)
{
for ($j=0; $j < 26 ; $j++)
{
$match=preg_match("/".$alpha_num[$j]."/",$string[$i]);
if($match==1)
{
$match_num[$i]=$alpha[$alpha_num[$j]];
$match_num[$i]+=$shift;
if($match_num[$i]>26)
{
$match_num[$i]=$match_num[$i]-26;
}
$encoded[$i]=$nums[$match_num[$i]];
}
}
$matchtwo=preg_match('/[^a-z]/',$string[$i]);
if($matchtwo==1)
{
$encoded[$i]=$string[$i];
}
}
$enc=implode('',$encoded);
return $enc;
}
else
{
return null;
}
}
AND last lets make these codes work on browsers--
Comments
Post a Comment