Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Created January 13, 2020 08:48
Show Gist options
  • Save addeeandra/de909aa1a1dfa5c742dfae9e020a3141 to your computer and use it in GitHub Desktop.
Save addeeandra/de909aa1a1dfa5c742dfae9e020a3141 to your computer and use it in GitHub Desktop.
SharedPreferences wrapper in secure way with encryption
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