Skip to content

Instantly share code, notes, and snippets.

@gauravssnl
Forked from scottyab/SampleEncPrefs.kt
Created January 30, 2024 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gauravssnl/803917898b4d6589135fef082de163b2 to your computer and use it in GitHub Desktop.
Save gauravssnl/803917898b4d6589135fef082de163b2 to your computer and use it in GitHub Desktop.
Simple example of using EncrypredSharedPreferences
package com.scottyab.whatsnewplayground.data
import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.scottyab.whatsnewplayground.BuildConfig
internal class SampleEncPrefs(context: Context) {
private val sharedPrefs: SharedPreferences
init {
val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)
sharedPrefs = EncryptedSharedPreferences
.create(
FILENAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
var userId: String
get() = sharedPrefs.getStringOrEmpty(USER_ID)
set(value) = sharedPrefs.edit().putString(USER_ID, value).apply()
var email: String
get() = sharedPrefs.getStringOrEmpty(EMAIL)
set(value) = sharedPrefs.edit().putString(EMAIL, value).apply()
var accessToken: String
get() = sharedPrefs.getStringOrEmpty(TOKEN)
set(value) = sharedPrefs.edit().putString(TOKEN, value).apply()
private fun SharedPreferences.getStringOrEmpty(key: String): String = getString(key, "") ?: ""
companion object {
private const val FILENAME = "my.secure.sharedPrefs"
private const val USER_ID = BuildConfig.APPLICATION_ID + ".USER_ID"
private const val EMAIL = BuildConfig.APPLICATION_ID + ".EMAIL"
private const val TOKEN = BuildConfig.APPLICATION_ID + ".TOKEN"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment