Caesar Cipher Program in Java

Caesar Cipher Program in Java: The Caesar Cipher technique is the simplest and oldest method of encryption in cryptography. In this technique, every character of the message is replaced by its next 3rd character.

For example, if the shift position is 3 then every character will be shifted by 3 positions to the right.

Plain:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Cipher:

D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
Algorithm for Caesar Cipher:
  1. Traverse the entire text letter by letter.
  2. On every iteration, the character is transformed as per the rule, depending upon whether you are encrypting or decrypting the text.
  3. Return the newly updated string.
Problem Statement

Write a Java program to perform the encryption and decryption of a message using the Ceaser Cipher technique.

Problem Solution

To perform the cipher technique in a given message, we have to find the integer value corresponding to the given text. Then we will use the modulo operator to perform the shift operation which does not exceed the limit of characters which is 0 to 25.

advertisement
advertisement

The corresponding integer value of each character is given below:

A B C D E F G H I J K L M
0 1 2 3 4 5 6 7 8 9 10 11 12
N O P Q R S T U V W X Y Z
13 14 15 16 17 18 19 20 21 22 23 24 25
Program/Source Code

Here is the source code of the Java Program to Implement Caesar Cipher. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * Java Program to Implement Caesar Cipher
 */
 
package com.sanfoundry.setandstring;
 
import java.util.Scanner;
 
public class CaesarCipher
{
    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
 
    public static String encrypt(String plainText, int shiftKey)
    {
        plainText = plainText.toLowerCase();
        String cipherText = "";
        for (int i = 0; i < plainText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(plainText.charAt(i));
            int keyVal = (shiftKey + charPosition) % 26;
            char replaceVal = ALPHABET.charAt(keyVal);
            cipherText += replaceVal;
        }
        return cipherText;
    }
 
    public static String decrypt(String cipherText, int shiftKey)
    {
        cipherText = cipherText.toLowerCase();
        String plainText = "";
        for (int i = 0; i < cipherText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
            int keyVal = (charPosition - shiftKey) % 26;
            if (keyVal < 0)
            {
                keyVal = ALPHABET.length() + keyVal;
            }
            char replaceVal = ALPHABET.charAt(keyVal);
            plainText += replaceVal;
        }
        return plainText;
    }
 
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the String for Encryption: ");
        String message = new String();
        message = sc.next();
        System.out.println(encrypt(message, 3));
        System.out.println(decrypt(encrypt(message, 3), 3));
        sc.close();
    }
}
Program Explanation

1. The program creates a class named “CaesarCipher”.
2. A constant string “ALPHABET” containing all the 26 letters of the English alphabet.
3. A function named “encrypt” that takes a plaintext and a shift key as input and returns the corresponding ciphertext. The function converts the plaintext to lowercase and replaces each character with another character in the alphabet which is a fixed number of positions ahead of the original character, determined by the shift key.
4. A function named “decrypt” that takes a ciphertext and a shift key as input and returns the corresponding plaintext. The function does the reverse of the “encrypt” function to obtain the original plaintext.
5. To use the program, the user inputs a message to be encrypted, which is then encrypted using the “encrypt” function with a shift key of 3.
6. The same ciphertext is then decrypted using the “decrypt” function with the same shift key of 3 to obtain the original plaintext.

Time Complexity: O(n)
Linear time complexity to encrypt and decrypt the text is O(n). Here, n is the length of the text.

Space Complexity: O(1)
It takes constant space to encrypt the text.

Run Time Testcases

In this case, we are encrypting and decrypting text using Caesar Cipher algorithm.

advertisement
$ javac CaesarCipher.java
$ java CaesarCipher
 
Enter the String for Encryption: 
Sanfoundry
vdqirxqgub
sanfoundry

Advantages of Caesar Cipher:

  • It is easy to build this message and message can be easily encrypted and decrypted in this method.
  • It provides minimum security to the information.
  • The system does not need to code is complicated.
  • It requires less number of computing resources.
  • It takes less time for encryption and decryption.

Disadvantages of Caesar Cipher:

  • It has a very simple structure usage.
  • It can only provide the minimum security to the information.
  • Security is a big issue with this method.

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.