How to Encrypt and Decrypt Text in Android Using Cryptography? - GeeksforGeeks

21 Jan, 2021
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”.
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:
Encryption: It is the process of transforming a readable message into an unreadable one. To do so we use encoding algorithms.Decryption: It is the process of transforming data or information from an unreadable to readable form. To do so we use decoding algorithms.
Encryption: It is the process of transforming a readable message into an unreadable one. To do so we use encoding algorithms.
Decryption: It is the process of transforming data or information from an unreadable to readable form. To do so we use decoding algorithms.
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
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 that select Java as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Modify the colors.xml file:
XML
<?xml version="1.0" encoding="utf-8"?> <resources>     <color name="colorPrimary">#6200EE</color>     <color name="colorPrimaryDark">#3700B3</color>     <color name="colorAccent">#03DAC5</color>     <color name="green">#0F9D58</color></resources>
Modify the style.xml file: Change the AppTheme to NoActionBar
XML
<resources>    <!-- Base application theme. -->    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">        <!-- Customize your theme here. -->        <item name="colorPrimary">@color/colorPrimary</item>        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>        <item name="colorAccent">@color/colorAccent</item>    </style></resources>
Create Java Class for Encode and Decode Algorithm:
We need to create two java classes each for encoding and decoding algorithms. To do so right-click and select the new Java class option and create them and name the file as Encode and Decode.
Create Empty Activities for Encryption and Decryption Screens:
We need to create two activities each for encryption and decryption screens. To do so right-click and select the new Empty Activity option and create both activities and name them as Encoder and Decoder.
Step 3: Create the Homepage of the app
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. Below is the code for the activity_main.xml file:
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#0F9D58"    android:orientation="vertical"    tools:context=".MainActivity">      <!--Title of the application-->    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_margin="5dp"        android:orientation="vertical">          <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:text="Cryptography App"            android:textColor="#FFFFFF"            android:textSize="40dp"            android:textStyle="bold" />      </LinearLayout>      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:layout_gravity="center"        android:layout_marginTop="30dp"        android:orientation="vertical">          <!--Button for encryption-->        <Button            android:id="@+id/btVar1"            android:layout_width="280dp"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_margin="50dp"            android:background="#000000"            android:text="Encryption"            android:textColor="#FFFFFF"            android:textSize="25dp"            android:textStyle="bold" />          <!--Button for decryption-->        <Button            android:id="@+id/btVar2"            android:layout_width="280dp"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_margin="50dp"            android:background="#000000"            android:text="Decryption"            android:textColor="#FFFFFF"            android:textSize="25dp"            android:textStyle="bold" />      </LinearLayout>  </RelativeLayout>
Output UI:
Step 4: Working with the MainActivity.java 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. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;  import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      Button enc, dec;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                  // link both the button variables with its id        enc = findViewById(R.id.btVar1);        dec = findViewById(R.id.btVar2);                  // onClick function for encryption        enc.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                // Intent function to move to another activity                Intent intent = new Intent(getApplicationContext(), Encoder.class);                startActivity(intent);            }        });          // onClick function for decryption        dec.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                // Intent function to move to another activity                Intent intent = new Intent(getApplicationContext(), Decoder.class);                startActivity(intent);            }        });    }}
Step 5: Add 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. Add the below code in the Java Class of Encode and Decode that we created in Step 2.
Encode.java: In this class, we have created a return function that will take a single parameter of a String variable and return an encrypted code in the form of String.
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: In this class, we have created a return function that will take a single parameter of a String variable of the encrypted code and return a decrypted text in the form of String.
Java
import android.util.Log;  public class Decode {    public static String decode(String s) {        String invalid = "Invalid Code";          // create the same initial        // string as in encode class        String ini = "11111111";        Boolean flag = true;          // run a loop of size 8        for (int i = 0; i < 8; i++) {            // check if the initial value is same            if (ini.charAt(i) != s.charAt(i)) {                flag = false;                break;            }        }        String val = "";          // reverse the encrypted code        for (int i = 8; i < s.length(); i++) {            char ch = s.charAt(i);            val = val.concat(String.valueOf(ch));        }          // create a 2 dimensional array        int arr[][] = new int[11101][8];        int ind1 = -1;        int ind2 = 0;          // run a loop of size of the encrypted code        for (int i = 0; i < val.length(); i++) {              // check if the position of the            // string if divisible by 7            if (i % 7 == 0) {                // start the value in other                // column of the 2D array                ind1++;                ind2 = 0;                char ch = val.charAt(i);                arr[ind1][ind2] = ch - '0';                ind2++;            } else {                // otherwise store the value                // in the same column                char ch = val.charAt(i);                arr[ind1][ind2] = ch - '0';                ind2++;            }        }        // create an array        int num[] = new int[11111];        int nind = 0;        int tem = 0;        int cu = 0;          // run a loop of size of the column        for (int i = 0; i <= ind1; i++) {            cu = 0;            tem = 0;            // convert binary to decimal and add them            // from each column and store in the array            for (int j = 6; j >= 0; j--) {                int tem1 = (int) Math.pow(2, cu);                tem += (arr[i][j] * tem1);                cu++;            }            num[nind++] = tem;        }        String ret = "";        char ch;        // convert the decimal ascii number to its        // char value and add them to form a decrypted        // string using conception function        for (int i = 0; i < nind; i++) {            ch = (char) num[i];            ret = ret.concat(String.valueOf(ch));        }        Log.e("dec", "text 11 - " + ret);          // check if the encrypted code was        // generated for this algorithm        if (val.length() % 7 == 0 && flag == true) {            // return the decrypted code            return ret;        } else {            // otherwise return an invalid message            return invalid;        }    }}
Step 6: Create the Encryption Layout
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.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#0F9D58"    android:orientation="vertical"    tools:context=".Encoder">      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="5dp"        android:orientation="vertical">          <!--title of the activity-->        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:text="Encrypter"            android:textColor="#FFFFFF"            android:textSize="40sp"            android:textStyle="bold" />      </LinearLayout>      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:orientation="vertical">          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginTop="5dp"            android:orientation="vertical">              <!--margin-->            <View                android:id="@+id/viewVar1"                android:layout_width="wrap_content"                android:layout_height="5dp"                android:background="#000000" />          </LinearLayout>          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="15dp"            android:layout_marginTop="10dp"            android:layout_marginRight="15dp"            android:layout_marginBottom="80dp"            android:orientation="vertical">              <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:text="Enter Your Text Here"                android:textColor="#FFFFFF"                android:textSize="20dp"                android:textStyle="bold" />              <!--input text for encryption-->            <EditText                android:id="@+id/etVar1"                android:layout_width="360dp"                android:layout_height="60dp"                android:layout_gravity="center"                android:layout_marginTop="5dp"                android:textColor="#FFFFFF"                android:textSize="20sp" />              <!--start encryption-->            <Button                android:id="@+id/btVar1"                android:layout_width="230dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:background="#000000"                android:onClick="enc"                android:text="Encrypt"                android:textColor="#FFFFFF"                android:textSize="20dp"                android:textStyle="bold" />          </LinearLayout>          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginTop="15dp"            android:orientation="vertical">              <!--margin-->            <View                android:id="@+id/viewVar2"                android:layout_width="wrap_content"                android:layout_height="5dp"                android:background="#000000" />          </LinearLayout>          <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="15dp"            android:layout_marginTop="5dp"            android:layout_marginRight="15dp"            android:orientation="vertical">              <!--display encrypted text here-->            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:text="Your encrypted text here : "                android:textColor="#FFFFFF"                android:textSize="20dp"                android:textStyle="bold" />              <TextView                android:id="@+id/tvVar1"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:textColor="#FAFAFA"                android:textSize="20dp" />          </LinearLayout>          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_margin="5dp"            android:layout_marginLeft="15dp"            android:layout_marginRight="15dp"            android:orientation="vertical">              <!--button to copy encrypted code-->            <Button                android:id="@+id/btVar3"                android:layout_width="230dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:background="#000000"                android:onClick="cp2"                android:text="Copy Text"                android:textColor="#FFFFFF"                android:textSize="20sp"                android:textStyle="bold" />          </LinearLayout>      </LinearLayout>  </RelativeLayout>
Output UI:
Step 7: Create the Decryption Layout
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.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#0F9D58"    android:orientation="vertical"    tools:context=".Decoder">      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:orientation="vertical">          <!--Textview to display title of the activity-->        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:text="Decrypter"            android:textColor="#FFFFFF"            android:textSize="40dp"            android:textStyle="bold" />      </LinearLayout>      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:layout_margin="5dp"        android:orientation="vertical">          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginTop="5dp"            android:orientation="vertical">              <!--view to create margin-->            <View                android:id="@+id/viewVar1"                android:layout_width="wrap_content"                android:layout_height="5dp"                android:background="#000000" />          </LinearLayout>          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="15dp"            android:layout_marginTop="10dp"            android:layout_marginRight="15dp"            android:layout_marginBottom="50dp"            android:orientation="vertical">              <!--enter the code to be decrypted here-->            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:text="Enter Your Text Here"                android:textColor="#FFFFFF"                android:textSize="20sp"                android:textStyle="bold" />              <EditText                android:id="@+id/etVar1"                android:layout_width="360dp"                android:layout_height="60dp"                android:layout_gravity="center"                android:layout_marginTop="5dp"                android:textColor="#FFFFFF"                android:textSize="20sp" />              <!--button to decrypt the code-->            <Button                android:id="@+id/btVar1"                android:layout_width="230dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:background="#000000"                android:onClick="dec"                android:text="Decrypt"                android:textColor="#FFFFFF"                android:textSize="20sp"                android:textStyle="bold" />          </LinearLayout>          <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginTop="15dp"            android:orientation="vertical">              <!--view to create margin-->            <View                android:id="@+id/viewVar2"                android:layout_width="wrap_content"                android:layout_height="5dp"                android:background="#000000" />          </LinearLayout>          <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="15dp"            android:layout_marginTop="5dp"            android:layout_marginRight="15dp"            android:orientation="vertical">              <!--display the decrypted text here-->            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:text="Your decrypted text is here : "                android:textColor="#FFFFFF"                android:textSize="20sp" />              <TextView                android:id="@+id/tvVar2"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="left"                android:layout_marginTop="5dp"                android:textColor="#FFFFFF"                android:textSize="20sp" />          </LinearLayout>          <LinearLayout              android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="15dp"            android:layout_marginTop="5dp"            android:layout_marginRight="15dp"            android:orientation="vertical">              <!--button to copy the decrypted text-->            <Button                android:id="@+id/btVar2"                android:layout_width="230dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:background="#000000"                android:onClick="cpl"                android:text="Copy Text"                android:textColor="#FFFFFF"                android:textSize="20sp"                android:textStyle="bold" />          </LinearLayout>      </LinearLayout>  </RelativeLayout>
Output UI:
Step 8: Working with the Encoder.java file
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.
Java
import android.content.ClipData;import android.content.ClipboardManager;import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;  import androidx.appcompat.app.AppCompatActivity;  public class Encoder extends AppCompatActivity {      EditText etenc;    TextView enctv;    ClipboardManager cpb;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_encoder);          // link the edittext and textview with its id        etenc = findViewById(R.id.etVar1);        enctv = findViewById(R.id.tvVar1);                  // create a clipboard manager variable to copy text        cpb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);    }      // onClick function of encrypt button    public void enc(View view) {        // get text from edittext        String temp = etenc.getText().toString();                  // pass the string to the encryption         // algorithm and get the encrypted code        String rv = Encode.encode(temp);                  // set the code to the edit text        enctv.setText(rv);    }      // onClick function of copy text button    public void cp2(View view) {        // get the string from the textview and trim all spaces        String data = enctv.getText().toString().trim();                  // check if the textview is not empty        if (!data.isEmpty()) {                          // copy the text in the clip board            ClipData temp = ClipData.newPlainText("text", data);            cpb.setPrimaryClip(temp);                          // display message that the text has been copied            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();        }    }}
Step 9: Working with the Decoder.java file
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.
Java
import android.content.ClipData;import android.content.ClipboardManager;import android.content.Context;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;  import androidx.appcompat.app.AppCompatActivity;  public class Decoder extends AppCompatActivity {      EditText etdec;    TextView dectv;    ClipboardManager cplboard;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_decoder);          // link the edittext and textview with its id        etdec = findViewById(R.id.etVar1);        dectv = findViewById(R.id.tvVar2);                  // create a clipboard manager variable to copy text        cplboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);    }      // onClick function of encrypt button    public void dec(View view) {        // get code from edittext        String temp = etdec.getText().toString();        Log.e("dec", "text - " + temp);                  // pass the string to the decryption algorithm         // and get the decrypted text        String rv = Decode.decode(temp);                  // set the text to the edit text for display        dectv.setText(rv);        Log.e("dec", "text - " + rv);    }      // onClick function of copy text button    public void cpl(View view) {                  // get the string from the textview and trim all spaces        String data = dectv.getText().toString().trim();                  // check if the textview is not empty        if (!data.isEmpty()) {                          // copy the text in the clip board            ClipData temp = ClipData.newPlainText("text", data);                          // display message that the text has been copied            Toast.makeText(this, "Copied", Toast.LENGTH_SHORT).show();        }    }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples