Skip to content

Instantly share code, notes, and snippets.

@sergei-mikhailovskii-idf
Created December 7, 2023 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergei-mikhailovskii-idf/30ba33eb1ed11ffa483bfff1ba89d5bd to your computer and use it in GitHub Desktop.
Save sergei-mikhailovskii-idf/30ba33eb1ed11ffa483bfff1ba89d5bd to your computer and use it in GitHub Desktop.
actual fun getNonEncryptedSettings(context: AppContext?): Settings = SharedPreferencesSettings(
PreferenceManager.getDefaultSharedPreferences(context)
)
actual fun getEncryptedSettings(context: AppContext?): Settings {
requireNotNull(context)
val masterKey = MasterKey.Builder(context)
.setKeyScheme(KeyScheme.AES256_GCM)
.build()
val encryptedPreferences = EncryptedSharedPreferences.create(
context,
context.packageName + "_encrypted_preferences",
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
val oldPreferences = getNonEncryptedSettings(context)
return SharedPreferencesSettings(MigrationPreferences(listOf("key1", "key2"), oldPreferences, encryptedPreferences))
}
class MigrationPreferences(
keysToMigrate: List<String>,
oldPreferences: Settings,
private val encryptedPreferences: SharedPreferences
) : SharedPreferences by encryptedPreferences {
init {
encryptedPreferences.edit {
keysToMigrate.forEach { key ->
val value = oldPreferences.getStringOrNull(key)
value?.let {
putString(key, it)
oldPreferences.remove(key)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment