Skip to content
Back to selected work

secure-storage-android: encrypted storage before Android had one

An open-source library for storing tokens and credentials safely on Android. 375 stars, 56 forks and millions of downloads.

Context

At adorsys I built Android apps for banks and insurers, including easyCredit / Fymio and Ergo Direkt. Apps like these hold login tokens and other credentials on the device, and those have to be stored safely.

Challenge

In the early years of Android there was no real answer to that. SharedPreferences stored values as plain text, and the platform offered no ready-made way to keep a token encrypted. Every team that cared had to work out the cryptography for itself, and getting cryptography slightly wrong is easy.

Approach

With help from a few teammates, I built a library that makes the safe path the short one. It generates a key inside the Android Keystore, encrypts each value with it, and writes only the encrypted result to SharedPreferences. On devices with a Trusted Execution Environment, the key is never exposed outside secure hardware, so the stored data stays protected even if the device is compromised.

How secure-storage-android stores a valueThe app hands a value to SecurePreferences. The library encrypts it with a key that is generated and kept inside the Android Keystore, then writes only the encrypted value to SharedPreferences. The key never leaves the Keystore.Your appsetValue()SecurePreferencesciphertextSharedPreferencesencrypt / decryptAndroid Keystorekey is generated hereand never leaves
Fig. 1: the key stays in the Keystore; only ciphertext reaches disk.

For the app developer it is one line to store a value and one to read it back:

SecurePreferences.setValue(context, "token", accessToken)
val token = SecurePreferences.getStringValue(context, "token", null)

It works from Android 4.3, using asymmetric keys for wide device coverage, with symmetric keys available from Android 6.0. We released it as open source under Apache 2.0, because the problem was not specific to our clients.

Outcome

The library reached millions of downloads, 375 stars and 56 forks on GitHub. The working students I mentored at adorsys contributed to it as well.

Years later Android shipped its own encrypted SharedPreferences, which superseded the library, and it is no longer maintained. I count that as the right ending: it covered a real gap for as long as the gap existed.