Open In App

How to Encrypt and Decrypt Text in Android Using Cryptography?

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

Cryptography is a technique of securing information and communications through the use of codes so that only those people for whom the information is intended can understand it and process it. Thus preventing unauthorized access to information. The prefix “crypt” means “hidden” and suffix graphy means “writing”.

img1

Project Overview

In this article, we will be building an Android Application that can Encrypt and Decrypt a message using the Encoding and Decoding algorithm respectively. The app's homepage will give the user two option:

  1. Encryption: It is the process of transforming a readable message into an unreadable one. To do so we use encoding algorithms.
  2. Decryption: It is the process of transforming data or information from an unreadable to readable form. To do so we use decoding algorithms.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note: Select Java/Kotlin as the programming language.

Step 2: Working with MainActivity and activity_main.xml file

In the MainActivity file, we will make the two buttons work in order to open the new activities. To do so we will use an Intent function that allows us to move from one activity to another. The two parameters of the Intent function are the current activity's class and the next activity's class. We will call this function inside onClickListener of the two buttons

The XML codes are used to build the structure of the activity as well as its styling part. On the homepage, we will have two buttons for Encryption and Decryption in the center of the activity. At the top, we will have a TextView for the title of the app.

MainActivity.java
package org.geeksforgeeks.demo;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private Button encodeButton;
    private Button decodeButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        encodeButton = findViewById(R.id.btVar1);
        decodeButton = findViewById(R.id.btVar2);

        encodeButton.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, Encoder.class);
            startActivity(intent);
        });

        decodeButton.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, Decoder.class);
            startActivity(intent);
        });
    }
}
MainActivity.kt activity_main.xml


Design UI:

cryptography-app-main


Step 3: Add Encode and Decode Algorithms

Create two Kotlin/Java file for encode and decode algorithms. Encoding algorithms are used to convert the text into an unreadable form, whereas Decoding algorithms are used to convert an encoded text into readable form. There are many algorithms that can be used to perform encryption and decryption. In this algorithm, we will be converting the text into a binary number using an Encryption algorithm. For this project, we will be using a customized algorithm. You can also use Base Type Encoding and Decoding Algorithms in Java.

Encode.java
public class Encode {
    public static String encode(String s) {
        // create a string to add in the initial
        // binary code for extra security
        String ini = "11111111";
        int cu = 0;
        
        // create an array
        int arr[] = new int[11111111];
        
        // iterate through the string
        for (int i = 0; i < s.length(); i++) {
            // put the ascii value of 
            // each character in the array
            arr[i] = (int) s.charAt(i);
            cu++;
        }
        String res = "";
        
        // create another array
        int bin[] = new int[111];
        int idx = 0;
        
        // run a loop of the size of string
        for (int i1 = 0; i1 < cu; i1++) {
            
            // get the ascii value at position
            // i1 from the first array
            int temp = arr[i1];
            
            // run the second nested loop of same size 
            // and set 0 value in the second array
            for (int j = 0; j < cu; j++) bin[j] = 0;
            idx = 0;
            
            // run a while for temp > 0
            while (temp > 0) {
                // store the temp module 
                // of 2 in the 2nd array
                bin[idx++] = temp % 2;
                temp = temp / 2;
            }
            String dig = "";
            String temps;
            
            // run a loop of size 7
            for (int j = 0; j < 7; j++) {
                
                // convert the integer to string
                temps = Integer.toString(bin[j]);
                
                // add the string using 
                // concatenation function
                dig = dig.concat(temps);
            }
            String revs = "";
            
            // reverse the string
            for (int j = dig.length() - 1; j >= 0; j--) {
                char ca = dig.charAt(j);
                revs = revs.concat(String.valueOf(ca));
            }
            res = res.concat(revs);
        }
        // add the extra string to the binary code
        res = ini.concat(res);
        
        // return the encrypted code
        return res;
    }
}
Decode.java Encode.kt Decode.kt


Step 4: Create the Encryption Layout

In the Encoder.java file, we will call the function that we created in the Step 5 (Encode.java) file. First, we will get the String from the EditText and then pass the value in the encode function. That will return us the encrypted code of the string. After that, we will set the code to a TextView and if it's not empty we will allow the user to copy the code in the clipboard. To perform the Encryption function onClick method is used in the button. Similarly, we have also set the onClick() function for copying the code in the clipboard for the button. Below is the code for the Encoder.java file. Comments are added inside the code to understand the code in more detail.

In the Encryption layout, we will have a TextView at top of the activity to display its title. Next, we will have a View to create a margin line. Next, there will be TextView and an EditText to input the text that is to be encrypted. Below that we will have a Button to encrypt the text. To display the encrypted code we have another TextView with a Button to copy it. Below is the XML code for the activity_encoder.xml file.

Encoder.java
package org.geeksforgeeks.demo;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class Encoder extends AppCompatActivity {
    private EditText editText;
    private TextView textView;
    private Button encryptButton, copyButton;
    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_encoder);

        // Link the UI components with their respective IDs
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.encryptedTextView);
        encryptButton = findViewById(R.id.encryptButton);
        copyButton = findViewById(R.id.copyButton);

        // Initialize clipboard manager
        clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        encryptButton.setOnClickListener(v -> {
            
            // Get user input
            String inputText = editText.getText().toString();
            
            // Call the encode function from the Encode class
            String encodedText = Encode.encode(inputText);
            
            // Display the encrypted text
            textView.setText(encodedText);
        });

        copyButton.setOnClickListener(v -> {
            
            // Get the text from the TextView
            String data = textView.getText().toString().trim();

            // Check if the TextView is not empty
            if (!data.isEmpty()) {
                
                // Copy the text to the clipboard
                ClipData copiedTextClip = ClipData.newPlainText("text", data);
                clipboardManager.setPrimaryClip(copiedTextClip);

                // Display a toast message that the text has been copied
                Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Encoder.kt activity_encoder.xml

Design UI:

cryptography-app-encrypt

Step 7: Create the Decryption Layout

In the Decoder.java file, we will call the function that we created in the Step 5 (Decode.java) file. First, we will get the encrypted code from the EditText and then pass the value in the decode function. That will return us the decrypted text of the string. After that, we will set the text to a TextView, and if it's not empty we will allow the user to copy the code in the clipboard. To perform the Decryption function onClick() method is used in the button. Similarly, we have also set the onClick() function for copying the code in the clipboard for the button. Below is the code for the Decoder.java file. Comments are added inside the code to understand the code in more detail.

In the Decryption layout, we will have a TextView at top of the activity to display its title. Next, we will have a View to create a margin line. Next, there will be TextView and an EditText to input the encrypted code that is to be decrypted. Below that we will have a Button to decrypt the text. To display the decrypted code we have another TextView with a Button to copy it. Below is the XML code for the activity_decoder.xml file.

Decoder.java
package org.geeksforgeeks.demo;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class Decoder extends AppCompatActivity {
    private EditText editText;
    private TextView textView;
    private Button decryptButton, copyButton;
    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_decoder);

        // Link UI components with their respective IDs
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.decryptedTextView);
        decryptButton = findViewById(R.id.decryptButton);
        copyButton = findViewById(R.id.copyButton);

        // Initialize clipboard manager
        clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        decryptButton.setOnClickListener(v -> {
            // Get the string from the edit text
            String inputText = editText.getText().toString();
            // Call the decode function from the Decode class
            String decodedText = Decode.decode(inputText);
            // Set the decoded text to the text view for display
            textView.setText(decodedText);
        });

        copyButton.setOnClickListener(v -> {
            // Get the text from the text view
            String data = textView.getText().toString().trim();

            // Check if the text view is not empty
            if (!data.isEmpty()) {
                // Copy the text to the clipboard
                ClipData copiedTextClip = ClipData.newPlainText("text", data);
                clipboardManager.setPrimaryClip(copiedTextClip);

                // Display a toast message that the text has been copied
                Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Decoder.kt activity_decoder.xml

Design UI:

cryptography-app-decrypt

Refer to the following github repo for the entire code: Encrypt_Decrypt_Text_Android

Output:



Next Article

Similar Reads