Skip to content

Commit

Permalink
clean alias and rerun if read/write failed
Browse files Browse the repository at this point in the history
Signed-off-by: phuoc <[email protected]>
  • Loading branch information
phuocbitmark committed Oct 9, 2024
1 parent f19f69c commit 6ff187f
Showing 1 changed file with 28 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ internal interface SecureFileStorage {
fun isExistingOnFilesDir(name: String): Boolean

fun deleteOnFilesDir(name: String): Boolean

fun cleanKeyStoreAlias()
}

internal class SecureFileStorageImpl(
Expand All @@ -30,21 +32,21 @@ internal class SecureFileStorageImpl(

private fun write(path: String, name: String, data: ByteArray) {
val file = getEncryptedFile("$path/$name", false)
try {
file.openFileOutput().apply {
write(data)
flush()
close()
}
} catch (
e: Exception
) {
Log.e("write error", "error: $e")
file.openFileOutput().apply {
write(data)
flush()
close()
}
}

override fun writeOnFilesDir(name: String, data: ByteArray) {
write(context.filesDir.absolutePath, getFileName(name), data)
try {
write(context.filesDir.absolutePath, getFileName(name), data)
} catch (e: Exception) {
Log.e("writeOnFilesDir", "error: $e")
cleanKeyStoreAlias()
write(context.filesDir.absolutePath, getFileName(name), data)
}
}

private fun read(path: String): ByteArray {
Expand All @@ -60,8 +62,13 @@ internal class SecureFileStorageImpl(
return os.toByteArray()
}

override fun readOnFilesDir(name: String): ByteArray =
override fun readOnFilesDir(name: String): ByteArray = try {
read(File(context.filesDir, getFileName(name)).absolutePath)
} catch (e: Exception) {
Log.e("readOnFilesDir", "error: $e")
cleanKeyStoreAlias()
read(File(context.filesDir, getFileName(name)).absolutePath)
}

private fun isExisting(path: String): Boolean = File(path).exists()

Expand All @@ -81,6 +88,15 @@ internal class SecureFileStorageImpl(
override fun deleteOnFilesDir(name: String): Boolean =
delete(File(context.filesDir, getFileName(name)).absolutePath)

override fun cleanKeyStoreAlias() {
val keyStore = KeyStore.getInstance(ANDROID_KEY_STORE).apply { load(null) }
val alias = keyStore.aliases().toList();
alias.forEach {
Log.d("alias", "alias: $it")
keyStore.deleteEntry(it)
}
}

private fun getEncryptedFile(path: String, read: Boolean) = File(path).let { f ->
if (f.isDirectory) throw IllegalArgumentException("do not support directory")
if (read && !f.exists() && !f.createNewFile()) {
Expand Down

0 comments on commit 6ff187f

Please sign in to comment.