How does secure data look like in Android?

Photo by King's Church International on Unsplash

Saving data in SharedPreference is so easy and comforting! But in programming, with every bit of laziness comes a threat. The same applies to SharedPreference. When we save our data in the android app using SharedPreference, it is easily available to hackers and malicious apps using easy tricks. Thus, this makes our SharedPreference non-useful when we have to save a password or some personal data of our user.

Let us understand this with example by storing data with SharedPreference.

  1. Create our file file and write this code:

2. We can use this file in the following way:

Now run the app, you will find that your data is saved in SharedPreference. But this data can be easily viewed from device file explorer. Anyone can find your data like this:

This is one way to easily use SharedPreference in any project. We can also create some other methods like saveIntValue() or getIntValue() to store or fetch integer value from our class.

Now we have seen how easy it is to store values in SharedPreference in Android! But our problem remains the same;

How to secure our DATA?

Our problem can be solved by using SharedPreference in modified form. We can use EncryptedSharedPreferences.

EncryptedSharedPreference stores our data the same as its parent SharedPreference but in encrypted form, so even if any middle man gets access to our SharedPreference, he won’t understand it. The EncryptedSharedPreference is available for SDK 23, so you still need another approach to secure your data in the lollipop version or below.

Let’s use EncryptedSharedPreference to secure our data.

  1. Add the dependency

2. Now Create our file file and write this code:

  1. We can use this file in the following way:

Now again run the app, you will find that your data is saved with EncryptedSharedPreference. This file can be viewed from device file explorer, but the data is encrypted:

You can see that our file is easily available, but the data is encrypted so it is impossible to get our data without the proper encryption key.

In this way, we can secure our data in android using EncryptedSharedPrefence. However, there is a major drawback of using this encrypted version of SharedPreference. Look carefully at the size of both the sharedpreference file: sharedpref.xml and encryptSharedPref.xml, the size of encryptSharedPref.xml is almost 10x of sharedpref.xml thus leading to comparatively poor performance.

So, use encrypted SharedPreference only when you are storing sensitive data, you can SharedPreference for common use cases.

Founder at Inside Android | Youtuber | App Developer