×

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of positions below the alphabet.

With such a shift of 1, for instance, X would become Y, Y would turn into Z, and so on. The first person to use it to communicate with his authorities was Julius Caesar. This method was given the name Caesar Cipher Method in honor of the man.

The ciphering of a given text requires an integer value. Each letter of a text has been shifted down a certain number of positions, as indicated by the integer value known as shift.

The following is how a shift n can be used to express the encrypting of a letter mathematically:

Shift n encryption phase: En (x) = (x+n)mod 26

Phase of decryption with n = Dn (x) = (x-n)mod 26

Examples

ABCDEFGHIJKLMNOPQRSTUVW XYZ : Text

Shift: 23

XYZABCDEFGHIJKLMNOPQRSTUVW is the cipher.

ATTACKATONCE: Text

Shift: 4

Encryption: EXXEGOEXSRGI

The following procedures are used to put the Caesar Cipher software into practice:

  • Take a user-supplied input string and encrypt it by employing the Caesar Cipher method.
  • For character shifting, ask the user for an input number. The input integer must range from 0 to 25.
  • Character by character, iterate through the supplied string.
  • We change each character in accordance with the rule based just on encryption and decoding.
  • brings back the freshly created string.

Let's put the code again for the Caesar Cipher approach into practice using the procedures that were just covered.

CaesarCipherExpl.java

// import all the required classes and also the packages   
import java.util.Scanner;   
// creating the class CaesarCipherExpl for decryption and encryption    
public class CaesarCipherExpl  
{   // alphabet string denotes alphabet from a to z  
    public static final String alphabet = "abcdefghijklmnopqrstuvwxyz";   
    // create encryptData() method for encrypting user iS with given sK  
    public static String encryptData(String iS, int sK)   
    {   // converting the iS into lower case   
        iS = iS.toLowerCase();   
        // eS to store encrypted data   
        String eS = "";   
        // use the for loop to traverse each character of the iS 
        for (int j = 0; j < iS.length(); j++)   
        {  // getting the position of each character of iS in the alphabet  
            int p = alphabet.indexOf(iS.charAt(j));   
            // getting eP for each char of iS   
            int eP = (sK + p) % 26;   
            char eC = alphabet.charAt(eP);   
            // adding eC to eS   
            eS += eC;   
        }  
        // returning the eS   
        return eS;   
    }   
    // create decryptData() method for decrypting user iS with given sK   
    public static String decryptData(String iS, int sK)   
    {   // converting the iS into lower case   
        iS = iS.toLowerCase();   
        // dS for storing the decrypted data   
        String dS = "";   
        // using the for loop for traversing each character of the iS  
        for (int j = 0; j < iS.length(); j++)   
    {   
           // get the position of each character of iS in the alphabet 
            int p = alphabet.indexOf(iS.charAt(j));   
            // get dC for each char of iS   
            int dP = (p - sK) % 26;   
            // if dP is negative   
            if (dP < 0){   
                dP = alphabet.length() + dP;   
            } 
            char dC = alphabet.charAt(dP);   
            // adding the dC to the dS   
            dS += dC;   
        }   
        // returning the dS   
        return dS;   
    }   
    // Driver code  
    public static void main(String[] args)   
   {
        // create an object for the Scanner class   
        Scanner s = new Scanner(System.in);   
        // taking input from the user   
        System.out.println(" Enter the following string to encrypt using the Caesar Cipher: ");   
        String iS = s.nextLine();   
        System.out.println(" The amount by which each character as in plaintext message is shifted should be entered is: ");   
        int sK = Integer.valueOf(s.nextLine());   
        System.out.println(" Encrypted Data === "+encryptData(iS, sK));   
        System.out.println(" Decrypted Data === "+decryptData(encryptData(iS, sK), sK));   
        // closing the Scanner class object   
        s.close();   
    }   
}   

Output:

Caesar Cipher Program in Java

Related Topics

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.