Phase 2: passphrase-encrypted backup and restore (PBKDF2 + AES-256-GCM)
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package io.github.abrarul.modularai.security
import android.content.Contextimport io.github.abrarul.modularai.data.AppDbimport io.github.abrarul.modularai.data.Captureimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport org.json.JSONArrayimport org.json.JSONObjectimport java.io.Fileimport java.security.SecureRandomimport javax.crypto.AEADBadTagExceptionimport javax.crypto.Cipherimport javax.crypto.SecretKeyFactoryimport javax.crypto.spec.GCMParameterSpecimport javax.crypto.spec.PBEKeySpecimport javax.crypto.spec.SecretKeySpec
/** File layout: magic "MAB1" | salt(16) | iv(12) | AES-256-GCM(JSON). Key = PBKDF2-HMAC-SHA256(passphrase). */object Backup { private val MAGIC = "MAB1".toByteArray() private const val ITER = 210_000
private fun key(pass: String, salt: ByteArray): SecretKeySpec { val f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") return SecretKeySpec(f.generateSecret(PBEKeySpec(pass.toCharArray(), salt, ITER, 256)).encoded, "AES") }
suspend fun export(ctx: Context, pass: String): File = withContext(Dispatchers.IO) { require(pass.length >= 8) { "Passphrase must be at least 8 characters" } val arr = JSONArray() AppDb.get(ctx).captures().list().forEach { arr.put(JSONObject().put("t", it.createdAt).put("text", Vault.decrypt(it.cipher))) } val salt = ByteArray(16).also { SecureRandom().nextBytes(it) } val c = Cipher.getInstance("AES/GCM/NoPadding") c.init(Cipher.ENCRYPT_MODE, key(pass, salt)) val body = c.doFinal(arr.toString().toByteArray(Charsets.UTF_8)) val dir = ctx.getExternalFilesDir(null) ?: ctx.filesDir File(dir, "backup-${System.currentTimeMillis()}.mab").also { it.writeBytes(MAGIC + salt + c.iv + body) } }
suspend fun restore(ctx: Context, file: File, pass: String): Int = withContext(Dispatchers.IO) { val raw = file.readBytes() require(raw.size > 4 + 16 + 12 + 16 && raw.copyOfRange(0, 4).contentEquals(MAGIC)) { "Not a ModularAI backup file" } val salt = raw.copyOfRange(4, 20) val iv = raw.copyOfRange(20, 32) val c = Cipher.getInstance("AES/GCM/NoPadding") c.init(Cipher.DECRYPT_MODE, key(pass, salt), GCMParameterSpec(128, iv)) val json = try { String(c.doFinal(raw, 32, raw.size - 32), Charsets.UTF_8) } catch (_: AEADBadTagException) { error("Wrong passphrase or damaged file") } val arr = JSONArray(json) val dao = AppDb.get(ctx).captures() for (i in 0 until arr.length()) { val o = arr.getJSONObject(i) dao.insert(Capture(createdAt = o.getLong("t"), cipher = Vault.encrypt(o.getString("text")))) } arr.length() }}app/src/main/java/io/github/abrarul/modularai/security/Backup.ktAdded+63