Android Studio Examples

100+ tutorials, source code, and examples to help you develop creative and technical skills.

Encryption and Decryption in Android using Java

activity_main.xml


/* Code From Learnoset - Learn Coding Online.
    Download Learnoset App from PlayStore to learn coding,
    projects, algorithms, error handling
 */

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/origionalString"
        android:hint="Original String"/>

    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Encrypt String"
        android:id="@+id/encryptStrBtn"
        android:layout_marginTop="20dp"/>
    <EditText
        android:layout_marginTop="40dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/encryptedString"
        android:hint="Encrypted String"/>
    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Decrypt String"
        android:id="@+id/decryptStrBtn"
        android:layout_marginTop="20dp"/>
    <EditText
        android:layout_marginTop="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/decryptedString"
        android:hint="Decrypted String"/>

</LinearLayout>

MainActivity.java

package com.learnoset.encryptdecrypt;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/* Code From Learnoset - Learn Coding Online.
    Download Learnoset App from PlayStore to learn coding,
    projects, algorithms, error handling
 */
 
public class MainActivity extends AppCompatActivity {

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

        final EditText originalStr = findViewById(R.id.origionalString);
        final EditText encryptedStr = findViewById(R.id.encryptedString);
        final EditText decryptedStr = findViewById(R.id.decryptedString);

        final AppCompatButton encryptStr = findViewById(R.id.encryptStrBtn);
        final AppCompatButton decryptStr = findViewById(R.id.decryptStrBtn);

        encryptStr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String originalStrTxt = originalStr.getText().toString();

                if(originalStrTxt.isEmpty()){
                    Toast.makeText(MainActivity.this, "Please enter original string", Toast.LENGTH_SHORT).show();
                }
                else{
                    final String encryptedString = encryptString(originalStrTxt);
                    encryptedStr.setText(encryptedString);
                }
            }
        });

        decryptStr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String encryptedStrTxt = encryptedStr.getText().toString();

                if(encryptedStrTxt.isEmpty()){
                    Toast.makeText(MainActivity.this, "Encrypted string is empty", Toast.LENGTH_SHORT).show();
                }
                else{
                    final String decryptedString = decryptString(encryptedStrTxt);
                    decryptedStr.setText(decryptedString);
                }
            }
        });
    }

    private String encryptString(String originalStr){
        String response = "";

        try {
            // string of 18 characters
            byte[] key = "1234567890ABCDEFGH".getBytes("UTF-8");

            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);

            // get 16 character from 18 characters
            key = Arrays.copyOf(key, 16);

            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            byte[] input = originalStr.getBytes("UTF-8");

            byte[] cipherTxt = cipher.doFinal(input);

            response = Base64.encodeToString(cipherTxt, Base64.DEFAULT);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return response;
    }

    public String decryptString(String encryptedString){
        String response = "";

        try {
            // string of 18 characters
            byte[] key = "1234567890ABCDEFGH".getBytes("UTF-8");

            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);

            // get 16 character from 18 characters
            key = Arrays.copyOf(key, 16);

            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

            byte[] input = encryptedString.getBytes("UTF-8");

            byte[] cipherTxt = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));

            response = new String(cipherTxt);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        return response;
    }
}

Projects with Source Code + Video Tutorials

You can download our Java and Android Studio Projects with Source Code and Video Tutorials.

Firebase-Push-Notifications-|-Background-Notification
Firebase Push Notifications | Background Notification
Custom-Navigation-bar-with-Material-UI-design
Custom Navigation bar with Material UI design
Online-Quiz-Application-using-Firebase-Realtime-Database-Source-Code
Online Quiz Application using Firebase Realtime Database Source Code

If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com

Follow us to learn Coding and get in touch with new Technologies.