Plaintext storage in Android SharedPreferences

Sensitive data stored in plaintext in Android SharedPreferences

Description

Plain SharedPreferences stores an app's token or session ID without encryption. Someone who obtains its preferences file from a backup, a rooted device, or a debug build may be able to read it.

Potential impact

A valid token can grant access to the account. Other preferences may reveal personal information or private app settings.

Remediation

Store sensitive values on the device only when needed. For new code, use a maintained encryption API and protect the key with Android Keystore. Check logs, backups, and debug output for copies of the plaintext.

Examples

The example uses EncryptedSharedPreferences, deprecated in AndroidX Security 1.1.0. It assumes a context and a Keystore-backed masterKey. Exclude the encrypted file from Auto Backup because the key may be unavailable after a restore.

Before

java
preferences.edit().putString("auth_token", token).apply();

After

java
SharedPreferences preferences = EncryptedSharedPreferences.create(
    context,
    "secure_prefs",
    masterKey,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
preferences.edit().putString("auth_token", token).apply();

The second example encrypts preference names and values on disk. A compromised app process may still read the decrypted token.

References