备份导出前置空校验,导入先选文件再输密码,版本/空备份校验、组id映射修复与 secret 查重统计
This commit is contained in:
@@ -3,25 +3,46 @@ package cn.airnan.a2fair.core.backup
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
import cn.airnan.a2fair.data.normalizeSecret
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.repository.TokenRepository
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonSyntaxException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.security.SecureRandom
|
||||
import javax.crypto.AEADBadTagException
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
const val BACKUP_VERSION = 1
|
||||
|
||||
class EmptyBackupException : Exception("backup is empty")
|
||||
|
||||
class UnsupportedBackupVersionException :
|
||||
Exception("backup version is newer than supported")
|
||||
|
||||
class WrongPasswordException : Exception("wrong backup password")
|
||||
|
||||
class InvalidBackupFileException : Exception("not a valid backup file")
|
||||
|
||||
data class BackupData(
|
||||
val version: Int = BACKUP_VERSION,
|
||||
val groups: List<Group>,
|
||||
val tokens: List<Token>
|
||||
)
|
||||
|
||||
data class ImportStats(
|
||||
val groupsImported: Int,
|
||||
val tokensImported: Int,
|
||||
val tokensSkipped: Int
|
||||
)
|
||||
|
||||
class BackupManager(
|
||||
private val context: Context,
|
||||
private val tokenRepository: TokenRepository,
|
||||
@@ -29,11 +50,16 @@ class BackupManager(
|
||||
) {
|
||||
private val gson = Gson()
|
||||
|
||||
suspend fun getTokenCount(): Int = tokenRepository.getAllTokens().first().size
|
||||
|
||||
suspend fun exportData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val tokens = tokenRepository.getAllTokens().first()
|
||||
if (tokens.isEmpty()) {
|
||||
return@withContext Result.failure(EmptyBackupException())
|
||||
}
|
||||
val groups = tokenRepository.getAllGroups().first()
|
||||
|
||||
|
||||
// Decrypt tokens before exporting
|
||||
val decryptedTokens = tokens.map { token ->
|
||||
token.copy(
|
||||
@@ -41,8 +67,8 @@ class BackupManager(
|
||||
// So token.secret is already decrypted!
|
||||
)
|
||||
}
|
||||
|
||||
val backupData = BackupData(groups, decryptedTokens)
|
||||
|
||||
val backupData = BackupData(groups = groups, tokens = decryptedTokens)
|
||||
val json = gson.toJson(backupData)
|
||||
val jsonBytes = json.toByteArray(Charsets.UTF_8)
|
||||
|
||||
@@ -74,50 +100,94 @@ class BackupManager(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun importData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
suspend fun importData(uri: Uri, password: CharArray): Result<ImportStats> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val encryptedBytes = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
input.readBytes()
|
||||
} ?: return@withContext Result.failure(Exception("Could not open input stream"))
|
||||
|
||||
var offset = 0
|
||||
val saltLength = encryptedBytes[offset++].toInt()
|
||||
val salt = encryptedBytes.copyOfRange(offset, offset + saltLength)
|
||||
offset += saltLength
|
||||
|
||||
val ivLength = encryptedBytes[offset++].toInt()
|
||||
val iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
|
||||
offset += ivLength
|
||||
|
||||
val data = encryptedBytes.copyOfRange(offset, encryptedBytes.size)
|
||||
|
||||
} ?: return@withContext Result.failure(InvalidBackupFileException())
|
||||
|
||||
val salt: ByteArray
|
||||
val iv: ByteArray
|
||||
val data: ByteArray
|
||||
try {
|
||||
var offset = 0
|
||||
val saltLength = encryptedBytes[offset++].toInt()
|
||||
salt = encryptedBytes.copyOfRange(offset, offset + saltLength)
|
||||
offset += saltLength
|
||||
|
||||
val ivLength = encryptedBytes[offset++].toInt()
|
||||
iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
|
||||
offset += ivLength
|
||||
|
||||
data = encryptedBytes.copyOfRange(offset, encryptedBytes.size)
|
||||
} catch (e: IndexOutOfBoundsException) {
|
||||
return@withContext Result.failure(InvalidBackupFileException())
|
||||
}
|
||||
|
||||
// Derive key
|
||||
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
val spec = PBEKeySpec(password, salt, 10000, 256)
|
||||
val secretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
|
||||
|
||||
// Decrypt
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
val gcmSpec = GCMParameterSpec(128, iv)
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec)
|
||||
val decryptedBytes = cipher.doFinal(data)
|
||||
|
||||
|
||||
// Decrypt; a GCM tag mismatch means the password is wrong
|
||||
val decryptedBytes = try {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
val gcmSpec = GCMParameterSpec(128, iv)
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec)
|
||||
cipher.doFinal(data)
|
||||
} catch (e: AEADBadTagException) {
|
||||
return@withContext Result.failure(WrongPasswordException())
|
||||
}
|
||||
|
||||
val json = String(decryptedBytes, Charsets.UTF_8)
|
||||
val backupData = gson.fromJson(json, BackupData::class.java)
|
||||
|
||||
// Merge logic (simple replace or merge)
|
||||
// For now, let's just insert all if not exists, or replace. We'll do a simple insert.
|
||||
val backupData = try {
|
||||
gson.fromJson(json, BackupData::class.java)
|
||||
} catch (e: JsonSyntaxException) {
|
||||
return@withContext Result.failure(InvalidBackupFileException())
|
||||
}
|
||||
|
||||
if (backupData.version > BACKUP_VERSION) {
|
||||
return@withContext Result.failure(UnsupportedBackupVersionException())
|
||||
}
|
||||
if (backupData.groups.isEmpty() && backupData.tokens.isEmpty()) {
|
||||
return@withContext Result.failure(EmptyBackupException())
|
||||
}
|
||||
|
||||
// Existing state for dedup and group name mapping
|
||||
val existingSecrets = tokenRepository.getAllTokens().first()
|
||||
.mapTo(mutableSetOf()) { it.secret.value.normalizeSecret() }
|
||||
val groupNameToId = tokenRepository.getAllGroups().first()
|
||||
.associate { it.name to it.id }
|
||||
.toMutableMap()
|
||||
|
||||
// Restore groups, dedup by name, build old-id -> new-id mapping
|
||||
val groupIdMapping = mutableMapOf<Long, Long>()
|
||||
var groupsImported = 0
|
||||
backupData.groups.forEach { group ->
|
||||
// Ensure group doesn't duplicate by name?
|
||||
// For simplicity, insert directly, handle id mapping later if needed.
|
||||
tokenRepository.insertGroup(group.copy(id = 0))
|
||||
val targetId = groupNameToId[group.name] ?: run {
|
||||
val newId = tokenRepository.insertGroup(group.copy(id = 0))
|
||||
groupNameToId[group.name] = newId
|
||||
groupsImported++
|
||||
newId
|
||||
}
|
||||
groupIdMapping[group.id] = targetId
|
||||
}
|
||||
|
||||
|
||||
// Restore tokens: dedup by normalized secret, remap groupId
|
||||
var tokensImported = 0
|
||||
var tokensSkipped = 0
|
||||
backupData.tokens.forEach { token ->
|
||||
tokenRepository.insertToken(token.copy(id = 0))
|
||||
if (token.secret.value.normalizeSecret() in existingSecrets) {
|
||||
tokensSkipped++
|
||||
return@forEach
|
||||
}
|
||||
val remappedGroupId = token.groupId?.let { groupIdMapping[it] }
|
||||
tokenRepository.insertToken(token.copy(id = 0, groupId = remappedGroupId))
|
||||
existingSecrets.add(token.secret.value.normalizeSecret())
|
||||
tokensImported++
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
|
||||
Result.success(ImportStats(groupsImported, tokensImported, tokensSkipped))
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
|
||||
@@ -5,3 +5,8 @@ data class SecretString(val value: String) {
|
||||
return "***"
|
||||
}
|
||||
}
|
||||
|
||||
/** Normalizes a base32 secret for comparison: uppercase, strip non-alphabet chars. */
|
||||
fun String.normalizeSecret(): String {
|
||||
return this.uppercase().replace(Regex("[^A-Z2-7]"), "")
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ fun BackupScreen(
|
||||
var confirmPassword by remember { mutableStateOf("") }
|
||||
var isExporting by remember { mutableStateOf(true) }
|
||||
var showPasswordDialog by remember { mutableStateOf(false) }
|
||||
var pendingImportUri by remember { mutableStateOf<Uri?>(null) }
|
||||
|
||||
val exportLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("application/octet-stream")
|
||||
@@ -40,6 +41,8 @@ fun BackupScreen(
|
||||
if (uri != null && password.isNotEmpty()) {
|
||||
scope.launch {
|
||||
val result = backupManager.exportData(uri, password.toCharArray())
|
||||
password = ""
|
||||
confirmPassword = ""
|
||||
if (result.isSuccess) {
|
||||
Toast.makeText(context, context.getString(R.string.export_successful), Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
@@ -52,15 +55,9 @@ fun BackupScreen(
|
||||
val importLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocument()
|
||||
) { uri: Uri? ->
|
||||
if (uri != null && password.isNotEmpty()) {
|
||||
scope.launch {
|
||||
val result = backupManager.importData(uri, password.toCharArray())
|
||||
if (result.isSuccess) {
|
||||
Toast.makeText(context, context.getString(R.string.import_successful), Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.import_failed, result.exceptionOrNull()?.message ?: ""), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (uri != null) {
|
||||
pendingImportUri = uri
|
||||
showPasswordDialog = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,8 +92,14 @@ fun BackupScreen(
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
isExporting = true
|
||||
showPasswordDialog = true
|
||||
scope.launch {
|
||||
if (backupManager.getTokenCount() == 0) {
|
||||
Toast.makeText(context, context.getString(R.string.backup_empty_tokens), Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
isExporting = true
|
||||
showPasswordDialog = true
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
@@ -117,7 +120,7 @@ fun BackupScreen(
|
||||
Button(
|
||||
onClick = {
|
||||
isExporting = false
|
||||
showPasswordDialog = true
|
||||
importLauncher.launch(arrayOf("application/octet-stream", "*/*"))
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
@@ -167,7 +170,35 @@ fun BackupScreen(
|
||||
if (isExporting) {
|
||||
exportLauncher.launch("a2fair_backup_${System.currentTimeMillis()}.bak")
|
||||
} else {
|
||||
importLauncher.launch(arrayOf("application/octet-stream", "*/*"))
|
||||
val uri = pendingImportUri
|
||||
pendingImportUri = null
|
||||
if (uri != null) {
|
||||
scope.launch {
|
||||
val result = backupManager.importData(uri, password.toCharArray())
|
||||
val stats = result.getOrNull()
|
||||
if (stats != null) {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.import_success_stats, stats.tokensImported, stats.tokensSkipped, stats.groupsImported),
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
} else {
|
||||
val messageRes = when (result.exceptionOrNull()) {
|
||||
is cn.airnan.a2fair.core.backup.EmptyBackupException -> R.string.import_empty_backup
|
||||
is cn.airnan.a2fair.core.backup.UnsupportedBackupVersionException -> R.string.import_unsupported_version
|
||||
is cn.airnan.a2fair.core.backup.WrongPasswordException -> R.string.import_wrong_password
|
||||
is cn.airnan.a2fair.core.backup.InvalidBackupFileException -> R.string.import_invalid_file
|
||||
else -> null
|
||||
}
|
||||
if (messageRes != null) {
|
||||
Toast.makeText(context, context.getString(messageRes), Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.import_failed, result.exceptionOrNull()?.message ?: ""), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
password = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -178,8 +209,9 @@ fun BackupScreen(
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
onClick = {
|
||||
showPasswordDialog = false
|
||||
pendingImportUri = null
|
||||
password = ""
|
||||
confirmPassword = ""
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.core.OtpUriParser
|
||||
import cn.airnan.a2fair.data.SecretString
|
||||
import cn.airnan.a2fair.data.normalizeSecret
|
||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
@@ -242,10 +243,6 @@ class TokensViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.normalizeSecret(): String {
|
||||
return this.uppercase().replace(Regex("[^A-Z2-7]"), "")
|
||||
}
|
||||
|
||||
private fun saveToken(token: Token) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user