Skip to content

Instantly share code, notes, and snippets.

@EhsanSetayesh
Created January 30, 2024 10:40
Show Gist options
  • Save EhsanSetayesh/fc95a45a2b7a6d239d3fade5c3b410e2 to your computer and use it in GitHub Desktop.
Save EhsanSetayesh/fc95a45a2b7a6d239d3fade5c3b410e2 to your computer and use it in GitHub Desktop.
const val PREF_NAME = "apiKeys"
const val PREF_DATA = "PREF_DATA"
class EncryptedPreferencesImpl(context: Context) : EncryptedPreferences {
private val masterKey = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build() as? MasterKey
private val preferences = masterKey?.let {
EncryptedSharedPreferences.create(
context,
PREF_NAME,
it,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
override fun saveEncryptedData(encryptedData: String): Boolean {
return if (preferences != null) {
preferences.edit {
putString(PREF_DATA, encryptedData)
}
true
} else false
}
override fun readEncryptedData(): String? {
val data = preferences?.getString(PREF_DATA, null)
return if (data != null) data
else null
}
override fun areApiKeysReady(): Boolean {
val firstCondition = preferences != null
&& preferences.contains(PREF_DATA)
val secondCondition = readEncryptedData() != null
return firstCondition && secondCondition
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment