Skip to content

Commit

Permalink
[APT-10955] SharedPref Crash Fix
Browse files Browse the repository at this point in the history
Nests the MasterKeys invocation, so that it does not crash on the 2nd attempt.
  • Loading branch information
kabliz committed Nov 4, 2024
1 parent 2841758 commit 071b506
Showing 1 changed file with 14 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fun SharedPreferences.deleteEncryptedSharedPreference(context: Context, filename
val deleted = sharedPrefsFile.delete()
Log.d(tag, "resetStorage() Shared prefs file deleted: $deleted; path: ${sharedPrefsFile.absolutePath}")
} else {
Log.d(tag,"resetStorage() Shared prefs file non-existent; path: ${sharedPrefsFile.absolutePath}")
Log.d(tag, "resetStorage() Shared prefs file non-existent; path: ${sharedPrefsFile.absolutePath}")
}

val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE_NAME)
Expand All @@ -41,7 +41,7 @@ fun SharedPreferences.deleteEncryptedSharedPreference(context: Context, filename

fun createEncryptedSharedPrefKeyStoreWithRetry(context: Context, fileName: String, keystoreAlias: String): SharedPreferences? {
val firstAttempt = createEncryptedSharedPrefsKeyStore(context = context, fileName = fileName, keystoreAlias = keystoreAlias)
return if(firstAttempt != null) {
return if (firstAttempt != null) {
firstAttempt
} else {
context.getSharedPreferences(fileName, Context.MODE_PRIVATE).deleteEncryptedSharedPreference(
Expand All @@ -61,25 +61,26 @@ fun createEncryptedSharedPrefsKeyStore(context: Context, fileName: String, keyst
.setEncryptionPaddings(ENCRYPTION_PADDING_NONE)
.build()

val keys = try {
MasterKeys.getOrCreate(keySpec)
} catch (ex: Exception) {
//clear corrupted store, contents will be lost
context.getSharedPreferences(fileName, Context.MODE_PRIVATE).deleteEncryptedSharedPreference(
context = context,
filename = fileName,
keystoreAlias = keystoreAlias )
MasterKeys.getOrCreate(keySpec)
}
return try {
val keys = try {
MasterKeys.getOrCreate(keySpec)
} catch (ex: Exception) {
//clear corrupted store, contents will be lost
context.getSharedPreferences(fileName, Context.MODE_PRIVATE).deleteEncryptedSharedPreference(
context = context,
filename = fileName,
keystoreAlias = keystoreAlias)
MasterKeys.getOrCreate(keySpec)
}

EncryptedSharedPreferences.create(
fileName,
keys,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
} catch(ex: Exception) {
} catch (ex: Exception) {
null
}
}

0 comments on commit 071b506

Please sign in to comment.