Wednesday 9 July 2014

Caesar Cipher Encryption and decryption concept

Caesar Cipher Encryption and decryption concept is very essential technique when working with Cryptography. The key values can be set on the basis of the programmers need. Here I have set the default key as 4 here. And my loop will cover 26 alphabets only... Hope it will help you...
*********************************************************************************

import javax.swing.JOptionPane;


public class Caesar_Cipher {

/* It is not needed to show our assumption explicitly */
    private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
    /* function _encrypt to encrypt the plain text with key value assumed
     * The key value assumed here is _shiftKey=4 indexed in main */
    public String encrypt(String plainText,int shiftKey)
    {
    /*converting to lower case as per the assumption*/
          plainText = plainText.toLowerCase();
          String cipherText="";
          for(int i=0;i<plainText.length();i++)
          {
               int charPosition = ALPHABET.indexOf(plainText.charAt(i));
               /* appending key value to the actual index */
               int keyVal = (shiftKey+charPosition)%26;
               char replaceVal = this.ALPHABET.charAt(keyVal);
               cipherText += replaceVal;
          }
          return cipherText;
    }
    public String decrypt(String cipherText, int shiftKey)
    {
          cipherText = cipherText.toLowerCase();
          String plainText="";
          for(int i=0;i<cipherText.length();i++)
          {
               int charPosition = this.ALPHABET.indexOf(cipherText.charAt(i));
               int keyVal = (charPosition-shiftKey)%26;
               if(keyVal<0)
               {
                     keyVal = this.ALPHABET.length() + keyVal;
               }
               char replaceVal = this.ALPHABET.charAt(keyVal);
               plainText += replaceVal;
          }
          return plainText;
    }
}

class CaesarDemo {
 

public static void main(String args[])
    {
  String plainText = (JOptionPane.showInputDialog("Input Data to encypt:"));
          int shiftKey=4;
       
          Caesar_Cipher cc = new Caesar_Cipher();
       
          String cipherText = cc.encrypt(plainText,shiftKey);
          System.out.println("Your Plain  Text :" + plainText);
          System.out.println("Your Cipher Text :" + cipherText);
       
          String cPlainText = cc.decrypt(cipherText,shiftKey);
          System.out.println("Your Plain Text  :" + cPlainText.replaceAll("z", " "));
    }
}

*****************************Thank You*******************************