Monday 20 February 2012

Caesar Cipher



In cryptography, a Caesar cipher, also known as a Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet
For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
 



The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain alphabet rotated left or right by some number of positions. For instance, here is a Caesar cipher using a left rotation of three places (the shift parameter, here 3, is used as the key):

Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher: DEFGHIJKLMNOPQRSTUVWXYZABC

When encrypting, a person looks up each letter of the message in the "plain" line and writes down the corresponding letter in the "cipher" line.
 
 
Deciphering is done in reverse.

Ciphertext: wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj
Plaintext: the quick brown fox jumps over the lazy dog

The encryption can also be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,..., Z = 25. Encryption of a letter x by a shift n can be described mathematically as,
 
 
Decryption is performed similarly,
 

(There are different definitions for the modulo operation. In the above, the result is in the range 0...25. I.e., if x+n or x-n are not in the range 0...25, we have to subtract or add 26.)
The replacement remains the same throughout the message, so the cipher is classed as a type of monoalphabetic substitution, as opposed to polyalphabetic substitution.
 
Java code for Encryption
(using a generic key and not fixed key)
 
for(i=0;i<inp.length();++i){
c=inp.charAt(i);
if(c>=65 && c<=90){
j=c-65;
j=(j+key)%26;
j=j+65;
k=(char)j;
out=out+k;
}
else if(c>=97 && c<=122){
j=c-97;
j=(j+key)%26;
j=j+97;
k=(char)j;
out=out+k;
}
else
out=out+c;
}

Java code for Decryption
 
for(i=0;i<inp.length();++i){
c=inp.charAt(i);
if(c>=65 && c<=90){
j=c-65;
j=(j-key)%26;
j=j+65;
k=(char)j;
out=out+k;
}
else if(c>=97 && c<=122){
j=c-97;
j=(j-key)%26;
j=j+97;
k=(char)j;
out=out+k;
}
else
out=out+c;
}

2 comments: