How to Encrypt Images in Android

M Farhan Majid
3 min readOct 17, 2021

--

If, for whatever reason, you want to encrypt images in your Android, Jetpack’s security library is the one for you!

In this article, we will make a simple application that picks an image from your storage and encrypt it.

Where’s the Source Code?

tl;dr

Jetpack’s security library allows you to encrypt and decrypt files within your app. This applies for image files too. One thing to notice is that this version of the library (1.1.0-alpha03) currently only supports API level ≥ 23.

If you run the app from this article, you will get the result below:

This simple application picks an image from storage and encrypt it. It then shows the two versions of the image: the original unencrypted version and the encrypted version.

Here, the user can pick an image from their storage and the app will save two versions of the image: the original unencrypted version and the encrypted version, and display them in an ImageView. As you can see, there are no noticeable differences between the two versions.

However, if you open the encrypted image (as shown in the image below), you will see that it has been encrypted and cannot be opened by a normal image viewer application.

The result of the image encryption. This file cannot be opened by normal image viewer application.

Step by Step Explanation

Follow the steps provided below to make a simple application.

1. Open Android Studio. Create new project with “Empty Activity” option. Set the Minimum SDK to API 23.

2. Add security and activity libraries to your app/build.gradle file. We need the activity library to enable picking images from user device. Here’s how it looks like:

3. First, we will make the layout first. Update the main_activity.xml as shown in the code below. As you can see, the layout consists of two buttons and two ImageViews. This app works this way: first user select an image by clicking “Select Image” button. And then user clicks “Read Image” button to display the previously selected image in two versions: original and encrypted.

Here’s what main_activity.xml looks like.

4. Lastly, we will update the MainActivity.kt file. You can copy paste the code below but here’s how it works basically: First we initialize MasterKey for encryption, the image picker, and the buttons’ on click listener. And within those listeners, we add the logic for encrypting and decrypting the image with Jetpack’s security library APIs. Notice that the main class here is EncryptedFile. It works quite similarly with normal File object, in which you will have access to InputStream and OutputStream objects.

5. And that’s it! Now you have created an app that encrypts an image for some reason.

Thanks for reading!

--

--

No responses yet