Open In App

Encryption and Decryption Application in Android using Caesar Cipher Algorithm

Last Updated : 25 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Here, we are going to make an application of “Encryption-decryption”. By making this application we will be able to learn that how we can convert a normal text to ciphertext and encrypt our message. We will also be decrypting our message with help of a key by again converting it to a readable form. This article will help you to introduce basic concepts of cryptography in android development.

Prerequisites:

Before proceeding with an application you should be aware of Caesar Cipher Algorithm of Cryptography. If you are not aware of it, use Caesar Cipher in Cryptography article to understand it.

What we are going to build in this article? 

In this application, we will provide a space(TextView) to display the output of encrypted or decrypted messages. The message, ciphertext, and key will be taken as input from the user. A java class named the utility will be made to write the logic for encryption and decryption buttons. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.

Now let see the step-by-step implementation of this application.

Step by Step Implementation

Step 1: Creating a new project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named as activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? 

Step 2: Working with activity_main.xml file

Here we will design the user interface of our application. We will be using the following components for their respective works:

  • TextView – to show output(encrypted or decrypted message).
  • EditText – to take input(message, ciphertext, and key).
  • Button – to encrypt or decrypt the message on click.

Navigate to the app > res > layout > activity_main.xml and add the below code to that file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#7AA4A8"
    tools:context=".MainActivity">
 
    <!-- This text view is used to show the
         output of encrypted or decrypted message  -->
    <TextView
        android:id="@+id/tV1"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_marginStart="27dp"
        android:layout_marginEnd="27dp"
        android:layout_marginBottom="25dp"
        android:background="#A8BDD1"
        android:gravity="center_vertical|center_horizontal"
        android:hint="Enter Your Text"
        android:padding="20dp"
        android:textColor="@color/black"
        android:textSize="40sp"
        app:layout_constraintBottom_toTopOf="@id/inputMessage"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tV2" />
 
    <!-- This text view is used to show
         the text "Caesar Cipher Algorithm" -->
    <TextView
        android:id="@+id/tV2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="42dp"
        android:layout_marginBottom="36dp"
        android:text="Caesar Cipher Algorithm"
        android:textColor="#070000"
        android:textSize="28sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@id/tV1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <!-- Button to perform the operations
         to encrypt the message-->
    <Button
        android:id="@+id/btnencrypt"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginStart="30dp"
        android:layout_marginEnd="30dp"
        android:background="#000000"
        android:text="Encrypt"
        android:textColor="#390F0F"
        android:textSize="18sp"
        android:textStyle="bold"
        app:backgroundTint="#A8BDD1"
        app:layout_constraintBaseline_toBaselineOf="@+id/btndecrypt"
        app:layout_constraintEnd_toStartOf="@+id/btndecrypt"
        app:layout_constraintStart_toStartOf="parent" />
 
    <!-- Button to perform the operations
         to decrypt the message-->
    <Button
        android:id="@+id/btndecrypt"
        android:layout_width="165dp"
        android:layout_height="49dp"
        android:layout_marginEnd="31dp"
        android:layout_marginRight="31dp"
        android:layout_marginBottom="90dp"
        android:background="@color/black"
        android:text="Decrypt"
        android:textColor="#421414"
        android:textSize="18sp"
        android:textStyle="bold"
        app:backgroundTint="#A8BDD1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/btnencrypt"
        app:layout_constraintTop_toBottomOf="@+id/key_dt" />
 
    <!-- Edit text to take input of message
         which user want to encrypt-->
    <EditText
        android:id="@+id/inputMessage"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:hint="Your Message"
        android:textColor="@color/black"
        app:layout_constraintBottom_toTopOf="@+id/ciphEdt"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tV2" />
 
    <!-- Edit text to take input of ciphertext
         using which encryption will be done -->
    <EditText
        android:id="@+id/ciphEdt"
        android:layout_width="356dp"
        android:layout_height="50dp"
        android:layout_marginStart="29dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="17dp"
        android:hint="Cipher Text"
        android:textColor="@color/black"
        app:layout_constraintBottom_toTopOf="@+id/key_dt"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputMessage" />
 
    <!-- Edit text to take input of key using
         which message will be decrypted -->
    <EditText
        android:id="@+id/key_dt"
        android:layout_width="356dp"
        android:layout_height="50dp"
        android:layout_marginStart="29dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="21dp"
        android:hint="Key"
        android:textColor="@color/black"
        app:layout_constraintBottom_toTopOf="@+id/btndecrypt"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ciphEdt" />
 
</androidx.constraintlayout.widget.ConstraintLayout>


After implementing the above code, the design of the activity_main.xml file looks like this.

Step 3: Creating a new java class

Create a new java class as shown below and name it as “utility“.

Step 4: Working with utility.java file

All the logic to encrypt and decrypt our message will be written in this class. Use the code provided below in this class:

Java




public class utility {
 
    // Declaration of all the required variables
    private static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static int index;
    private static int updated_index;
    private static int final_index;
    private static int index_p_t_l;
    private static int index_s_t_l;
    private static String plainTxt;
    private static String cipherTxt;
    private static String finalTxt;
 
    // code for encryption
    public static String encrypt1(String plaintext, int encrptionKey) {
        reset();
        // plaintext is converted to uppercase
        // so that it is easy to convert according
        // to Caesar Cipher algorithm
        plaintext = plaintext.toUpperCase();
        // using a for loop the use index and
        // change text with help of it
        for (index = 0; index < plaintext.length(); index++) {
            // checking the condition for plaintext to be
            // null at some character position
            if (plaintext.charAt(index) != ' ') {
                index_p_t_l = alphabet.indexOf(plaintext.charAt(index));
                // index is being updated
                // so that next and final index
                // be used for ciphertext
                updated_index = encrptionKey + alphabet.indexOf(plaintext.charAt(index));
                if (updated_index >= alphabet.length()) {
                    final_index = updated_index - alphabet.length();
                } else
                    final_index = updated_index;
                // substring is used so that every character
                // can be separately converted to ciphertext
                cipherTxt = alphabet.substring(final_index, final_index + 1);
                finalTxt = finalTxt + cipherTxt;
            }
        }
        // returning the
        // final changed text
        return finalTxt;
    }
 
    // code for decryption
    public static String decrypt1(String ciphertext, int decryptionKey) {
        reset();
        ciphertext = ciphertext.toUpperCase();
        // using a for loop the use index and
        // change text with help of it
        for (index = 0; index < ciphertext.length(); index++) {
            if (ciphertext.charAt(index) != ' ') {
                index_p_t_l = alphabet.indexOf(ciphertext.charAt(index));
                index_s_t_l = index_p_t_l;
                // index is updated with help of decryption
                // key which we provided as input
                updated_index = alphabet.indexOf(ciphertext.charAt(index)) - decryptionKey;
                if (updated_index < 0) {
                    final_index = updated_index + alphabet.length();
                } else
                    final_index = updated_index;
                // reverse of encryption is done as
                // substring here is used to convert
                // each ciphertext character to plaintext
                plainTxt = alphabet.substring(final_index, final_index + 1);
                finalTxt += plainTxt;
            }
        }
        // returning the
        // final changed text
        return finalTxt;
    }
 
    // method to reset the text
    // in the output textview
    private static void reset() {
        finalTxt = "";
    }
}


Step 5: Working with MainActivity.java file

In MainActivity.java file onClickListener is used on buttons of encryption and decryption and methods from the utility class are directly passed here. Use the following code in the MainActivity.java file.

Java




import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
 
    // declaring all essential variables
    private Button encrypt, decrypt;
    private EditText message, cipher, key;
    private TextView screen_output;
    private static final String alphabetString = "abcdefghijklmnopqrstuvwxyz";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // findViewById is the method that
        // finds the View by the ID it is given
        encrypt = findViewById(R.id.btnencrypt);
        decrypt = findViewById(R.id.btndecrypt);
        screen_output = findViewById(R.id.tV1);
        message = findViewById(R.id.inputMessage);
        cipher = findViewById(R.id.ciphEdt);
        key = findViewById(R.id.key_dt);
 
        // setting onCLickListener on encrypt button
        encrypt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                encrypt12(message.getText().toString(), Integer.parseInt(key.getText().toString()));
            }
        });
 
        // setting onCLickListener on decrypt button
        decrypt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                decrypt12(cipher.getText().toString(), Integer.parseInt(key.getText().toString()));
            }
        });
    }
 
    // method to show the final output on the output
    // textView when decrypt button is clicked
    public void decrypt12(String cipher, int key) {
        screen_output.setText((utility.decrypt1(cipher, key).toLowerCase()));
    }
 
    // method to show the final output on the output
    // textView when encrypt button is clicked
    public String encrypt12(String message, int shiftkey) {
        message = message.toLowerCase();
        String cipherText = "";
        for (int i = 0; i < message.length(); i++) {
            int charPosition = alphabetString.indexOf(message.charAt(i));
            int keyval = (shiftkey + charPosition) % 26;
            char replaceVAL = alphabetString.charAt(keyval);
            cipherText += replaceVAL;
            screen_output.setText(cipherText);
            cipher.setText(cipherText);
        }
 
        // returning the final ciphertext
        return cipherText;
    }
}


Congratulations!! you have successfully made the encryption and decryption application using Caesar Cipher Algorithm. Here is the final output of our application.

Output:

Note: Do not enter the key number more than 26 because we have used the Caesar Cipher Algorithm for 26 alphabets. The app may crash if the key is more than 26.

GitHub link: https://github.com/Karan-Jangir/caesar_cipher_algorithm_crytography



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads