AIM: Write JAVA Program for encryption and decryption of Caesar Cipher.

 

Caesar cipher

Caesar cipher, also known as shift cipher, is one of the easiest ways to crucify. It is a cipher instead of each letter in the first message (called plain text) replaced by a letter corresponding to a certain number of letters above or below the letter.

 

Algorithm:

Caesar Cipher can be expressed mathematically as follows:

En(x) = (x+n) mod 26

In simple terms, this means that the encryption of the letter x is equal to the change of x + n, where n is the number of characters that have been moved. The result of the process is then subtracted under the module division, which means that when a character is moved past the end of a letter, it wraps it up at the beginning i.e., we start at a.

Encryption of encrypted text (ciphertext) is the opposite, we just subtract it to get the original text.

Dn(x) = (x-n) mod 26


Program:

import java.util.Scanner;

public class CaesarCipher

{

  public static void main (String args[])

  {

    Scanner sc = new Scanner (System.in);

    int shift, i, n;

    String str;

    String str1 = "";

    String str2 = "";

      System.out.println ("Enter the plaintext");

      str = sc.nextLine ();

      str = str.toLowerCase ();

      n = str.length ();

    char ch1[] = str.toCharArray ();

    char ch3, ch4;

      System.out.

      println

      ("Enter the value by which each letter of the string is to be shifted");

      shift = sc.nextInt ();

      System.out.println ();

      System.out.println ("Encrypted text is");

    for (i = 0; i < n; i++)

      {

   if (Character.isLetter (ch1[i]))

     {

       ch3 = (char) (((int) ch1[i] + shift - 97) % 26 + 97);

       //System.out.println(ch1[i]+" = "+ch3);

       str1 = str1 + ch3;

     }

   else if (ch1[i] == ' ')

     {

       str1 = str1 + ch1[i];

     }

      }

    System.out.println (str1);

    System.out.println ();

    System.out.println ("Decrypted text is");

    char ch2[] = str1.toCharArray ();

    for (i = 0; i < str1.length (); i++)

      {

   if (Character.isLetter (ch2[i]))

     {

       if (((int) ch2[i] - shift) < 97)

         {

               ch4 = (char) (((int) ch2[i] - shift - 97 + 26) % 26 + 97);

         }

       else

         {

               ch4 = (char) (((int) ch2[i] - shift - 97) % 26 + 97);

         }

       str2 = str2 + ch4;

     }

   else if (ch2[i] == ' ')

     {

       str2 = str2 + ch2[i];

     }

      }

    System.out.println (str2);

  }

}


Output: