Android
Encrypted Token Storage on Android with EncryptedSharedPreferences and Hilt
Plain SharedPreferences stores tokens as cleartext in a world-readable XML file. This post covers a production TokenStore backed by EncryptedSharedPreferences, lazily initialised and injected as a Hilt singleton.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 2 of 5Android Foundations
- Three Retrofit Clients in One Android App with Hilt Qualifiers
- Encrypted Token Storage on Android with EncryptedSharedPreferences and Hilt
- Seeding a Room Database via ADB BroadcastReceiver in Kotlin
- Printing Labels from Android Using the Brother QL SDK
- Android Project Docs with MkDocs, Dokka, and Firebase Hosting
Storing a JWT access token in plain SharedPreferences means it sits as
cleartext in an XML file under the app’s data directory. On a rooted device
or via an ADB backup, that file is readable. EncryptedSharedPreferences from
the AndroidX Security library encrypts both keys and values using AES256 before
writing to disk. This post covers a TokenStore that wraps it — lazily
initialised to defer the key derivation cost off the main thread, injected as
a Hilt singleton, and structured so callers never interact with preference keys
directly.
Prerequisites
Kotlin 2.0, Hilt 2.56, androidx.security:security-crypto. minSdk 23,
compileSdk 36. The security-crypto library depends on Tink under the hood —
no explicit Tink dependency needed.
Background
SharedPreferences on Android is stored as an XML file at
/data/data/<package>/shared_prefs/<filename>.xml. The file is protected by
Linux filesystem permissions — only the app’s UID can read it under normal
conditions. This is not sufficient for tokens:
- Rooted devices can read any file as root
adb backupcan extract shared_prefs from apps that allow backup (restricted for apps targeting Android 12+, but still common in the field)FLAG_ALLOW_BACKUP(on by default) allows cloud backup of shared_prefs, which means tokens can appear in Google Drive backup storage
EncryptedSharedPreferences encrypts each key with AES256-SIV and each value
with AES256-GCM before the XML is written. The master key lives in the Android
Keystore, which is hardware-backed on devices that support it.
Implementation
1. Dependency
dependencies { implementation(libs.security.crypto) // "androidx.security:security-crypto:1.1.0-alpha06" implementation(libs.hilt.android) ksp(libs.hilt.compiler)}2. TokenStore
@Singletonclass TokenStore @Inject constructor( @ApplicationContext context: Context) { private val prefs by lazy { val masterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build()
EncryptedSharedPreferences.create( context, "brickworks_secure_prefs", masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) }
fun getAccessToken(): String = prefs.getString(KEY_ACCESS_TOKEN, "") ?: "" fun setAccessToken(token: String) = prefs.edit { putString(KEY_ACCESS_TOKEN, token) }
fun getRefreshToken(): String = prefs.getString(KEY_REFRESH_TOKEN, "") ?: "" fun setRefreshToken(token: String) = prefs.edit { putString(KEY_REFRESH_TOKEN, token) }
fun getStoreID(): String = prefs.getString(KEY_STORE_ID, "") ?: "" fun setStoreID(id: String) = prefs.edit { putString(KEY_STORE_ID, id) }
fun getVerificationToken(): String = prefs.getString(KEY_VERIFICATION_TOKEN, "") ?: "" fun setVerificationToken(token: String) = prefs.edit { putString(KEY_VERIFICATION_TOKEN, token) }
fun isLoggedIn(): Boolean = getAccessToken().isNotBlank()
fun clearTokens() = prefs.edit { clear() }
companion object { private const val KEY_ACCESS_TOKEN = "access_token" private const val KEY_REFRESH_TOKEN = "refresh_token" private const val KEY_STORE_ID = "store_id" private const val KEY_VERIFICATION_TOKEN = "verification_token" }}MasterKey.Builder replaces the older MasterKeys.getOrCreate() helper,
which is deprecated. All preference key constants are private. Nothing outside TokenStore
knows what the keys are — callers use typed methods. This prevents silent
key-name mismatches across the codebase.
3. Hilt wiring
@Singleton and @Inject constructor are all Hilt needs. No @Module or
@Provides required — Hilt generates the binding automatically.
@BrickWorks@Provides@Singletonfun providesBrickWorksOkHttpClient( tokenStore: TokenStore, // injected directly — no module needed loggingInterceptor: HttpLoggingInterceptor,): OkHttpClient { val authInterceptor = Interceptor { chain -> val token = tokenStore.getAccessToken() val request = chain.request().newBuilder() .apply { if (token.isNotBlank()) { addHeader("Authorization", "Bearer $token") } } .build() chain.proceed(request) } return OkHttpClient.Builder() .addInterceptor(authInterceptor) .addInterceptor(loggingInterceptor) .build()}The OkHttp interceptor reads from TokenStore on every request. Because
TokenStore is a singleton and prefs is by lazy, the EncryptedSharedPreferences
instance is created once and reused across all subsequent reads. The lazy
initialisation is thread-safe — Kotlin’s lazy delegate uses LazyThreadSafetyMode.SYNCHRONIZED
by default.
4. Auth flow usage
After OTP verification, the auth ViewModel writes both tokens in sequence:
fun onVerifyOtp(otp: String) { viewModelScope.launch(Dispatchers.IO) { val result = storeRepository.verifyOtp(otp) result.onSuccess { response -> tokenStore.setAccessToken(response.accessToken) tokenStore.setRefreshToken(response.refreshToken) tokenStore.setStoreID(response.storeId) _loginState.value = LoginState.Success }.onFailure { _loginState.value = LoginState.Error(it.message) } }}clearTokens() handles logout — one call wipes all encrypted entries:
fun logout() { viewModelScope.launch(Dispatchers.IO) { tokenStore.clearTokens() _loginState.value = LoginState.LoggedOut }}Testing
./gradlew connectedAndroidTest --tests "*.TokenStoreTest"
BUILD SUCCESSFUL in 6s5 instrumented tests completedEncryptedSharedPreferences requires an actual Android environment — the
Keystore is not available in unit tests. Use instrumented tests on a real
device or emulator. For unit tests of auth logic, mock TokenStore directly.
Pitfalls
Production considerations
AES256_SIV for key encryption is deterministic — the same key string always
encrypts to the same ciphertext. This is required because SharedPreferences uses
the encrypted key as a map key. AES256-GCM for values is non-deterministic
(random IV per write), which provides stronger confidentiality for values at
the cost of slightly larger storage.
The master key lives in the Android Keystore. It is hardware-backed (TEE, or StrongBox on devices that have it) where the device supports it, and software-backed otherwise. The library handles this transparently — you do not need to branch on API level or device.
If your app uses allowBackup="true" in the manifest, add a backup rule that
excludes the encrypted prefs file. Including it in a backup is dangerous — the
master key is not backed up, so the restored file would be unreadable, and
the encrypted data would be present in backup storage without its key.
Android 12 replaced the old format, so you need two files: one for
Android 11 and below, and data_extraction_rules.xml (referenced by
android:dataExtractionRules) for Android 12+.
<full-backup-content> <exclude domain="sharedpref" path="brickworks_secure_prefs.xml" /></full-backup-content><data-extraction-rules> <cloud-backup> <exclude domain="sharedpref" path="brickworks_secure_prefs.xml" /> </cloud-backup> <device-transfer> <exclude domain="sharedpref" path="brickworks_secure_prefs.xml" /> </device-transfer></data-extraction-rules>Wrapping up
You now have a Hilt-injected TokenStore backed by EncryptedSharedPreferences:
lazily initialised to keep key derivation off the main thread, typed accessors
that hide preference keys from callers, and a single clearTokens() for logout.
The full implementation is in TokenStore.kt.
The natural next step is an OkHttp Authenticator that calls the refresh
endpoint when a 401 response arrives and retries the original request with
the new access token — the TokenStore methods above are everything it needs.
Going deeper
Jetpack Security Crypto is now deprecated. In 2025 Google deprecated
androidx.security:security-crypto, recommending direct use of the Android
Keystore and Tink instead. Existing apps keep working, but new code should
not start here. The replacement is short:
- Create a Tink
Aeadwhose keyset is stored in app storage, wrapped by a key in the Android Keystore (AndroidKeysetManagerwith aandroid-keystore://master key URI). - Store tokens in Jetpack DataStore, encrypting the serialized value with
aead.encrypt(plaintext, associatedData)on write and decrypting on read.
DataStore also fixes two SharedPreferences problems: its API is
asynchronous (no main-thread disk I/O), and writes are transactional.
Encryption at rest is one layer, not the whole story. On a rooted device an attacker can call into your running app and ask it to decrypt. Shorten the damage window instead: short-lived access tokens, rotating refresh tokens that are invalidated on reuse, and server-side revocation on logout.
Bind tokens to the device for high-value apps. For banking-grade threat models, a non-exportable Keystore key can sign each request (or a DPoP-style proof), so a stolen token is useless without the hardware key it is bound to.