Created
July 24, 2019 20:12
-
-
Save scottyab/5012ab75454a777a60ec433661aafa8b to your computer and use it in GitHub Desktop.
Simple example of using EncrypredSharedPreferences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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