Skip to content

Commit

Permalink
Fix error when app preferences create (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
l2hyunwoo authored Jul 24, 2023
1 parent 679bd98 commit 0a63606
Showing 1 changed file with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(),
Expand Down

0 comments on commit 0a63606

Please sign in to comment.