Monday, August 27, 2012

Implementing adaptive ceasar cipher

In this tutorial we will see how to implement ceaser cipher in an adaptive way. Normal ceasar cipher uses a fixed length to shift the characters. Example we shift characters by fixed units example shift by 5 characters or 7 characters. We will make this algorithm adaptive by making this shifting unit variable. This unit can be based on length of the string. Here is how you will do it.


function adaptivecipher(tocipher)
{
var word_cipher = tocipher;
var word_cipher_length = tocipher.length;
var stepper = word_cipher_length;
var char_library = '0123456789abcdefghijklmnopqrstuvwxyz';
var char_library_length = charset.length;
var cipherText = "";

/*Loop and shift replace the characters*/
var index = word_cipher_length - 1;
for(;index >= 0;index--)
{
var realchar = word_cipher.charAt(index);
var place_in_char_library = char_library.indexOf(realchar);
if(place_in_char_library != -1)
{
var newcharposition = place_in_char_library+stepper;
if(newcharposition <= char_library_length)
{cipherText = char_library.charAt(newcharposition) + cipherText;}
else
{cipherText = char_library.charAt((newcharposition - char_library_length)-1) + cipherText;}
}
}
return cipherText;
}

If we want further make it effective we can shuffle the order in character library.