Created
January 13, 2020 08:48
-
-
Save addeeandra/de909aa1a1dfa5c742dfae9e020a3141 to your computer and use it in GitHub Desktop.
SharedPreferences wrapper in secure way with encryption
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 android.content.SharedPreferences | |
import androidx.security.crypto.EncryptedSharedPreferences | |
import androidx.security.crypto.MasterKeys | |
import com.example.app.BuildConfig | |
class SecurePreferences(context: Context) { | |
private val _encryptedSharedPreferences: SharedPreferences | |
init { | |
val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC | |
val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec) | |
val secureFile = BuildConfig.SECURE_NAME | |
_encryptedSharedPreferences = EncryptedSharedPreferences.create( | |
secureFile, | |
masterKeyAlias, | |
context, | |
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, | |
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM | |
) | |
} | |
fun SecurePreferences.edit(callable: SharedPreferences.Editor.() -> Unit) { | |
_encryptedSharedPreferences | |
.edit() | |
.apply { callable() } | |
.apply() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment