EncryptedSharedPreferences: Secure Key-Value Storage on Android
EncryptedSharedPreferences is a drop-in replacement for SharedPreferences that automatically encrypts keys and values, protecting sensitive data at rest. Use it to store small, sensitive data like API tokens. The main footgun is mismanaging the master key.
WHY IT EXISTS: Standard SharedPreferences stores data in a plain-text XML file in an app's private directory. On a rooted device, this file is easily readable, exposing any sensitive information like API keys stored within. EncryptedSharedPreferences was created to mitigate this security vulnerability by providing encryption at rest by default.
THE MENTAL MODEL: Think of it as a SharedPreferences object with a built-in, non-removable lockbox. You interact with it using the familiar edit(), putString(), and getString() methods, but behind the scenes, every piece of data is scrambled before being written to the file and unscrambled when read.
HOW IT WORKS: EncryptedSharedPreferences is part of the AndroidX Security library. When you create an instance, you provide a MasterKey. This key, ideally stored in the hardware-backed Android Keystore, is used to derive subkeys for encryption. It uses Google's robust Tink cryptography library to perform AES-256-GCM encryption for values and a deterministic encryption scheme for keys, ensuring both are unreadable in the stored XML file.
WHEN TO USE IT: Use it for storing small amounts of sensitive data that need to persist across app sessions. Good candidates include authentication tokens, refresh tokens, user identifiers, or small, sensitive user settings. It's a direct, secure replacement for SharedPreferences in these cases.
WHEN NOT TO USE IT: Avoid it for large datasets; the overhead of encrypting and decrypting large values can impact performance. For storing large structured data securely, use an encrypted database like Room with SQLCipher. Do not use it for non-sensitive data, as the performance cost is unnecessary.
ONE CANONICAL EXAMPLE: Storing a user's OAuth 2.0 access token. This token grants access to a user's account on a remote service and must be kept secret. Storing it in standard SharedPreferences is a major security risk. Using EncryptedSharedPreferences ensures that even if an attacker gains root access and reads the app's files, the token remains encrypted and unusable.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.