×

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 String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 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 Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.