Skip to content

Instantly share code, notes, and snippets.

@mzennis
Last active December 24, 2024 07:48
Show Gist options
  • Save mzennis/26d10513829efe9b5e3e7a6c8fe08d01 to your computer and use it in GitHub Desktop.
Save mzennis/26d10513829efe9b5e3e7a6c8fe08d01 to your computer and use it in GitHub Desktop.
Sample Implementation of: EncryptedSharedPreferences
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
class SecurePreferences private constructor(context: Context, prefName: String) {
companion object {
fun create(context: Context): SecurePreferences {
return SecurePreferences(context, "secure_prefs")
}
}
private val sharedPreferences by lazy {
val masterKey = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
EncryptedSharedPreferences.create(
/* context = */ context,
/* fileName = */ prefName,
/* masterKey = */ masterKey,
/* prefKeyEncryptionScheme = */ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
/* prefValueEncryptionScheme = */ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
fun saveString(key: String, value: String?) {
sharedPreferences.edit().putString(key, value).apply()
}
fun getString(key: String, defaultValue: String? = null): String? {
return sharedPreferences.getString(key, defaultValue)
}
fun clearPreferences() {
sharedPreferences.edit().clear().apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment