Caesar Cipher Encrption and Decryption in java

     Caesar Cipher -a simplest form of encryption and decryption technique. Each letter is substituted by another letter. The substitution is based on shifting. for eg: ‘A’ is substituted by ‘E’ and so on is shift of 4.

This technique was used by Julius Caesar for communicating in military operations.

Let us implement this in java language.

Program implementation:

              This program implementation starts with including Built in header file import java.util.Scanner;.

A public class is created with encryption and decryption methods.

Encryption:encryptIt()

  • This function creates an object for StringBuilder.
  • Each character is separated and check for uppercase or lowercase.
  • According to it, the shifting value is added, and appropriate alphabet is replaced.

Decrption:decryptIt()

              This reads the character in the String and replace the alphabet by previous alphabet according to the shifting value.

‘main()’:

  •               This function reads the text to decrypted and shifting value from user. Call the encrypt and decrypt function.
  • Finally, print both values.

Program:

import java.util.Scanner;

public class CaesarCipherEg {

    // Encryption method

    public static String encryptIt(String txt, int shift) {

        StringBuilder encrypTex = new StringBuilder();

        for (char cha : txt.toCharArray()) {

            if (Character.isLetter(cha)) {

                char base1 = Character.isUpperCase(cha) ? 'A' : 'a';

                encrypTex.append((char) ((cha - base1 + shift) % 26 + base1));

            } else {

                encrypTex.append(cha);

            }

        }

        return encrypTex.toString();

    }

 

    // Decryption method

    public static String decryptIt(String txt, int shift) {

        return encryptIt(txt, 26 - (shift % 26));

    }

     public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        System.out.println("Enter the text to be encrypted");

        String p_text = s1.nextLine();

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

        int shift = s1.nextInt();

         String encrypTex = encryptIt(p_text, shift);

        String decrypTex = decryptIt(encrypTex, shift);

         System.out.println("Encrypted: " + encrypTex);

        System.out.println("Decrypted: " + decrypTex);

    }

}

Output:

C:\raji\blog>javac CaesarCipherEg.java

C:\raji\blog>java CaesarCipherEg

Enter the text to be encrypted

Welcome to Java

Enter the shift

2

Encrypted: Ygneqog vq Lcxc

Decrypted: Welcome to Java

This is the way of creating classic Caesar cipher encryption and decryption program in java. Hope this code is useful to you!!!

No comments:

Post a Comment