Sun. Jan 20th, 2019

Encryption using Java Android Cryptography API

Encryption using Java Android Cryptography API | In this tutorial, we’ll learn how to use Android cryptography API provided by Java, in Android. Before starting with code lets first see the packages provided by Java for cryptography.

  • javax.crypto: This package provides the classes and interfaces for cryptographic applications implementing algorithms for encryption, decryption, or key agreement.
  • javax.crypto.interfaces: This package provides the interfaces needed to implement the key agreement algorithm.
  • javax.crypto.spec: This package provides the classes and interfaces needed to specify keys and parameter for encryption.

I’ve also added links to official documentation for above packages. Using these packages we can implement many encryption algorithms like AES, DES, RSA, SHA etc. In this tutorial, we’ll see the most popular and widely used AES algorithm. So let’s get started.

Sample output:

Sample project: Encryption

Sample APK: Encryption_1.0

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating a New Project: Android cryptography API

Open your Android Studio & create a new Project, give name whatever you like and We’ll keep all the things by default and clicked finish.

No need for extra permission or third-party libraries for this project.

Add following code to your main activity’s java file.

MainActivity.java

package com.shah.kaushal28.encryption;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {

    TextView o,e,d;

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

        o = (TextView)findViewById(R.id.original);
        e = (TextView)findViewById(R.id.encrypted);
        d = (TextView)findViewById(R.id.decrypted);


        try{
            crypto();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public void crypto() throws Exception{
        byte[] input = "Kaushal Shah".getBytes();
//        byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04,
//                0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
//                0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
//                0x15, 0x16, 0x17 };

        byte[] keyBytes = "abcdefghijklmnop".getBytes();

        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

        System.out.println(new String(input));
        o.setText("Original: " + new String(input));


        // encryption pass
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
        System.out.println(new String(cipherText));
        e.setText("Encrypted: " + new String(cipherText));
        System.out.println(ctLength);

        // decryption pass
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
        int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
        ptLength += cipher.doFinal(plainText, ptLength);
        System.out.println(new String(plainText));
        d.setText("Decrypted: "+ new String(plainText));
        System.out.println(ptLength);
    }
}

activity_main.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.shah.kaushal28.encryption.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/original" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/original"
        android:id="@+id/encrypted" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/encrypted"
        android:id="@+id/decrypted" />
</RelativeLayout>

Note the key length of the encryption. You need to specify the key length of 256/192/128 bits only because key size is fixed in AES encryption. If you are providing key length other than mentioned bits, you will end up with an exception. See the commented key input. You can provide this type of bytes also. But generally, we prefer readable keys like one I’ve used here. If you are providing this type of text instead of the byte array, then keep in mind that 1 character means 8bits. To provide key length accordingly. Also, you need to convert that into a byte array using method “getBytes()”.

Related:

Android Real Time Face detection and Prediction using Google Mobile Vision API

Image Recognition Using Google’s API

Parsing XML data using Retrofit2 API

Parsing the Json Data using Android Retrofit Api and display in Recyclerview with Cardview

Note: In the sample output, you can see the unreadable characters. It’s not an error. Then are ASCII characters only.If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Leave a Reply

Your email address will not be published. Required fields are marked *