×

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

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

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.

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.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.