Last active
December 24, 2024 07:48
-
-
Save mzennis/26d10513829efe9b5e3e7a6c8fe08d01 to your computer and use it in GitHub Desktop.
Sample Implementation of: EncryptedSharedPreferences
This file contains hidden or 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
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