androidsecurityencryptionsharedpreferenceskeystore

Which is more secure: EncryptedSharedPreferences or storing directly in KeyStore?


I'm looking for a secure way to store a shared secret in my Android app.

SharedPreferences is not secure because data is stored unencrypted and can be easily accessed on rooted devices.

I've read about using KeyStore and EncryptedSharedPreferences for secure storage. EncryptedSharedPreferences encrypts data before storing it in SharedPreferences, and the encryption key is stored in KeyStore.

I'm confused about whether I should use EncryptedSharedPreferences or store the shared secret directly in KeyStore. Which approach is more secure and why?


Solution

  • KeyStore is a system-wide service in Android that provides cryptographic operations and secure storage for keys. It's designed to securely generate and store cryptographic keys, and it's often used to protect data encryption keys rather than directly storing shared secrets or other sensitive data.

    EncryptedSharedPreferences, on the other hand, is a wrapper around SharedPreferences that encrypts the keys and values before storing them. The encryption key used by EncryptedSharedPreferences is stored in KeyStore, which means the shared secret itself isn't stored directly in KeyStore, but it's encrypted using a key that is.

    So, Using EncryptedSharedPreferences would be the recommended approach because it's specifically designed for this purpose. The encryption key used by EncryptedSharedPreferences is securely stored in KeyStore, providing an additional layer of security.

    Here's a simple example of how you can use EncryptedSharedPreferences:

    String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
    SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
        "secret_shared_prefs",
        masterKeyAlias,
        context,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    );
    
    // use the shared preferences and editor as you normally would
    SharedPreferences.Editor editor = sharedPreferences.edit();
    

    I also recommend you to explore topic such as Android’s Security library and Obfuscation