From 0a636061f0a8f365861a000ba718f3c539c84a05 Mon Sep 17 00:00:00 2001 From: "HyunWoo Lee (Nunu Lee)" <54518925+l2hyunwoo@users.noreply.github.com> Date: Mon, 24 Jul 2023 16:00:09 +0900 Subject: [PATCH] Fix error when app preferences create (#227) --- .../pophory/config/di/PreferencesModule.kt | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/teampophory/pophory/config/di/PreferencesModule.kt b/app/src/main/java/com/teampophory/pophory/config/di/PreferencesModule.kt index 5923773f..d2fba493 100644 --- a/app/src/main/java/com/teampophory/pophory/config/di/PreferencesModule.kt +++ b/app/src/main/java/com/teampophory/pophory/config/di/PreferencesModule.kt @@ -13,6 +13,8 @@ import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent +import java.security.GeneralSecurityException +import java.security.KeyStore import javax.inject.Singleton @Module @@ -28,9 +30,33 @@ object PreferencesModule { ): SharedPreferences = if (BuildConfig.DEBUG) { context.getSharedPreferences(DEBUG_APP_PREFERNCES_NAME, Context.MODE_PRIVATE) } else { - EncryptedSharedPreferences.create( + try { + createEncryptedSharedPreferences(APP_PREFERENCES_NAME, context) + } catch (e: GeneralSecurityException) { + deleteMasterKeyEntry() + deleteExistingPref(APP_PREFERENCES_NAME, context) + createEncryptedSharedPreferences(APP_PREFERENCES_NAME, context) + } + } + + private fun deleteExistingPref(fileName: String, context: Context) { + context.deleteSharedPreferences(fileName) + } + + private fun deleteMasterKeyEntry() { + KeyStore.getInstance("AndroidKeyStore").apply { + load(null) + deleteEntry(MasterKey.DEFAULT_MASTER_KEY_ALIAS) + } + } + + private fun createEncryptedSharedPreferences( + fileName: String, + context: Context + ): SharedPreferences { + return EncryptedSharedPreferences.create( context, - APP_PREFERENCES_NAME, + fileName, MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build(),