DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Encrypted SharedPreferences: Secure Data Storage in Android

Protecting sensitive user data is critical. EncryptedSharedPreferences from Jetpack Security provides transparent encryption for SharedPreferences.

Setting Up EncryptedSharedPreferences

import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey

fun getEncryptedPreferences(context: Context): SharedPreferences {
    val masterKey = MasterKey.Builder(context)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()

    return EncryptedSharedPreferences.create(
        context,
        "secret_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
}
Enter fullscreen mode Exit fullscreen mode

Storing and Retrieving Encrypted Data

@Composable
fun SecureDataScreen(context: Context) {
    val prefs = remember { getEncryptedPreferences(context) }

    Button(
        onClick = {
            prefs.edit().putString("api_token", "secret_token_123").apply()
        }
    ) {
        Text("Save Token")
    }

    Button(
        onClick = {
            val token = prefs.getString("api_token", "")
            println("Token: $token")
        }
    ) {
        Text("Retrieve Token")
    }
}
Enter fullscreen mode Exit fullscreen mode

Using DataStore for Modern Approach

DataStore is the modern replacement for SharedPreferences:

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = "secure_data",
    produceMigrations = ::EncryptedSharedPreferencesMigration
)

@Composable
fun DataStoreExample(context: Context) {
    val apiToken = context.dataStore.data
        .map { prefs -> prefs[stringPreferencesKey("api_token")] ?: "" }
        .collectAsState(initial = "")

    Button(
        onClick = {
            context.dataStore.edit { prefs ->
                prefs[stringPreferencesKey("api_token")] = "new_token"
            }
        }
    ) {
        Text("Update Token")
    }
}
Enter fullscreen mode Exit fullscreen mode

Encrypted storage protects user privacy and builds trust in your app.


8 Android app templates available on Gumroad

Top comments (0)