Modern Apps git

← Modern-Apps.git

backup: add BIP39 recovery code and AES-256-GCM crypto core

Commit
46a4f6c9c67edac7fa995a5318dd437c0f8d2e58
Author
Vayun Mathur <[email protected]>
When
2026-08-12 19:00 UTC (3 months ago)
Parents
9cec55f

Diff

backup/LICENSE-Seedvault
diff --git a/backup/LICENSE-Seedvault b/backup/LICENSE-Seedvaultnew file mode 100644index 0000000000..6008150948--- /dev/null+++ b/backup/LICENSE-Seedvault@@ -0,0 +1,36 @@+Portions of the Backup app reimplement concepts from Seedvault, the encrypted+backup application for Android:++    https://github.com/seedvault-app/seedvault++Seedvault's application code is distributed under the Apache License 2.0. The+ported concepts here are the recovery-code scheme (a BIP-0039 12-word mnemonic+deriving a 512-bit seed via PBKDF2-HMAC-SHA512), the segmented AES-256-GCM+on-disk backup format, and the overall app-data backup transport design. This+is an independent Kotlin reimplementation, not a copy of Seedvault's source, but+attribution is retained per the established convention in this repository (see+networklocation/src/main/rust/LICENSE-GrapheneOS).++The BIP-0039 English wordlist bundled at+backup/src/main/resources/bip39-english.txt is the canonical list from the+Bitcoin BIPs repository (public domain / BSD-2-Clause):++    https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt++                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   Copyright The Seedvault Contributors++   Licensed under the Apache License, Version 2.0 (the "License"); you may not+   use these concepts' originating files except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+   License for the specific language governing permissions and limitations+   under the License.
backup/src/main/java/com/vayunmathur/backup/crypto/Bip39.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/crypto/Bip39.kt b/backup/src/main/java/com/vayunmathur/backup/crypto/Bip39.ktnew file mode 100644index 0000000000..998aad1945--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/crypto/Bip39.kt@@ -0,0 +1,124 @@+package com.vayunmathur.backup.crypto++import java.security.MessageDigest+import java.security.SecureRandom+import java.text.Normalizer+import javax.crypto.SecretKeyFactory+import javax.crypto.spec.PBEKeySpec++/**+ * BIP-0039 mnemonic recovery codes: entropy ⇔ 12-word mnemonic and mnemonic →+ * 512-bit seed (PBKDF2-HMAC-SHA512). This mirrors the recovery-code scheme used by+ * Seedvault so a backup is recoverable from the twelve words alone.+ *+ * Ported concept (BIP-0039 + Seedvault recovery code) — see backup/LICENSE-Seedvault.+ * The 2048-word English wordlist is loaded from the bundled resource+ * `/bip39-english.txt` (canonical Bitcoin BIPs list).+ */+object Bip39 {+    /** BIP-0039 salt prefix for the PBKDF2 seed derivation. */+    private const val SEED_SALT_PREFIX = "mnemonic"+    private const val PBKDF2_ITERATIONS = 2048+    private const val SEED_BITS = 512++    /** 12-word code: 128 bits of entropy + a 4-bit checksum = 132 bits = 12 × 11. */+    const val ENTROPY_BYTES = 16+    const val WORD_COUNT = 12++    val wordList: List<String> by lazy { loadWordList() }+    private val wordIndex: Map<String, Int> by lazy {+        wordList.withIndex().associate { (i, w) -> w to i }+    }++    private fun loadWordList(): List<String> {+        val stream = Bip39::class.java.getResourceAsStream("/bip39-english.txt")+            ?: error("bip39-english.txt not found on classpath")+        val words = stream.bufferedReader(Charsets.UTF_8).use { reader ->+            reader.readLines().map { it.trim() }.filter { it.isNotEmpty() }+        }+        require(words.size == 2048) { "BIP-39 wordlist must have 2048 words, got ${words.size}" }+        return words+    }++    /** A fresh random 12-word recovery code. */+    fun generate(): List<String> =+        entropyToMnemonic(ByteArray(ENTROPY_BYTES).also { SecureRandom().nextBytes(it) })++    /** Encodes [entropy] (16/20/24/28/32 bytes) as its BIP-0039 mnemonic. */+    fun entropyToMnemonic(entropy: ByteArray): List<String> {+        require(entropy.size in intArrayOf(16, 20, 24, 28, 32)) {+            "entropy must be 16/20/24/28/32 bytes, got ${entropy.size}"+        }+        val checksumBits = entropy.size * 8 / 32+        val hash = sha256(entropy)+        val bits = BooleanArray(entropy.size * 8 + checksumBits)+        for (i in entropy.indices) for (b in 0 until 8) {+            bits[i * 8 + b] = (entropy[i].toInt() shr (7 - b)) and 1 == 1+        }+        // checksumBits ≤ 8 for all valid sizes, so it fits in hash[0].+        for (b in 0 until checksumBits) {+            bits[entropy.size * 8 + b] = (hash[0].toInt() shr (7 - b)) and 1 == 1+        }+        return (0 until bits.size / 11).map { group ->+            var idx = 0+            for (j in 0 until 11) idx = (idx shl 1) or (if (bits[group * 11 + j]) 1 else 0)+            wordList[idx]+        }+    }++    /** Decodes a mnemonic back to its entropy, verifying the checksum. */+    fun mnemonicToEntropy(mnemonic: List<String>): ByteArray {+        require(mnemonic.isNotEmpty() && mnemonic.size % 3 == 0) {+            "mnemonic length must be a positive multiple of 3"+        }+        val totalBits = mnemonic.size * 11+        val checksumBits = totalBits / 33+        val entropyBits = totalBits - checksumBits+        val bits = BooleanArray(totalBits)+        for ((i, word) in mnemonic.withIndex()) {+            val idx = wordIndex[word] ?: throw IllegalArgumentException("word not in list: $word")+            for (j in 0 until 11) bits[i * 11 + j] = (idx shr (10 - j)) and 1 == 1+        }+        val entropy = ByteArray(entropyBits / 8)+        for (i in entropy.indices) {+            var value = 0+            for (j in 0 until 8) value = (value shl 1) or (if (bits[i * 8 + j]) 1 else 0)+            entropy[i] = value.toByte()+        }+        val hash = sha256(entropy)+        for (b in 0 until checksumBits) {+            val expected = (hash[0].toInt() shr (7 - b)) and 1 == 1+            if (bits[entropyBits + b] != expected) {+                throw IllegalArgumentException("invalid recovery-code checksum")+            }+        }+        return entropy+    }++    /** True if [mnemonic] is a well-formed BIP-0039 code with a valid checksum. */+    fun isValid(mnemonic: List<String>): Boolean =+        runCatching { mnemonicToEntropy(mnemonic) }.isSuccess++    /**+     * Derives the 512-bit BIP-0039 seed from a mnemonic (NFKD-normalized) and an+     * optional passphrase, via PBKDF2-HMAC-SHA512 with 2048 iterations.+     */+    fun mnemonicToSeed(mnemonic: List<String>, passphrase: String = ""): ByteArray {+        val mnemonicStr = Normalizer.normalize(mnemonic.joinToString(" "), Normalizer.Form.NFKD)+        val salt = Normalizer.normalize(SEED_SALT_PREFIX + passphrase, Normalizer.Form.NFKD)+        val spec = PBEKeySpec(+            mnemonicStr.toCharArray(),+            salt.toByteArray(Charsets.UTF_8),+            PBKDF2_ITERATIONS,+            SEED_BITS,+        )+        return try {+            SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512").generateSecret(spec).encoded+        } finally {+            spec.clearPassword()+        }+    }++    private fun sha256(data: ByteArray): ByteArray =+        MessageDigest.getInstance("SHA-256").digest(data)+}
backup/src/main/java/com/vayunmathur/backup/crypto/Crypto.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/crypto/Crypto.kt b/backup/src/main/java/com/vayunmathur/backup/crypto/Crypto.ktnew file mode 100644index 0000000000..6a298b773a--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/crypto/Crypto.kt@@ -0,0 +1,125 @@+package com.vayunmathur.backup.crypto++import com.vayunmathur.e2ee.E2ee+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * Segmented AES-256-GCM encryption for backup blobs. A payload is split into+ * fixed-size segments, each sealed independently with [E2ee.aesEncrypt] (fresh+ * random IV, `iv||ciphertext||tag`) under the same master key. Each segment's+ * plaintext is prefixed with its 4-byte index, so any reordering, duplication, or+ * truncation of segments is detected on decrypt (in addition to GCM's per-segment+ * integrity). Wrong key or tampering surfaces as an [javax.crypto.AEADBadTagException].+ *+ * On-disk stream layout:+ * ```+ * [1 byte  version = 1]+ * repeated: [4-byte BE segmentLen][segmentLen bytes: E2ee(iv||ct||tag)]+ * ```+ * where each segment plaintext = `[4-byte BE index][data chunk ≤ SEGMENT_SIZE]`.+ *+ * Ported concept (Seedvault segmented backup format) — see backup/LICENSE-Seedvault.+ */+class Crypto(private val masterKey: ByteArray) {+    init {+        require(masterKey.size == 32) { "master key must be 32 bytes (AES-256)" }+    }++    fun encrypt(input: InputStream, output: OutputStream) {+        output.write(VERSION)+        val buffer = ByteArray(SEGMENT_SIZE)+        var index = 0+        while (true) {+            val read = fill(input, buffer)+            if (read == 0) break+            val plain = ByteArray(4 + read)+            writeIntBE(plain, 0, index)+            buffer.copyInto(plain, 4, 0, read)+            val segment = E2ee.aesEncrypt(masterKey, plain)+            writeIntTo(output, segment.size)+            output.write(segment)+            index+++            if (read < SEGMENT_SIZE) break+        }+        output.flush()+    }++    fun decrypt(input: InputStream, output: OutputStream) {+        val version = input.read()+        if (version < 0) throw IOException("empty backup stream")+        require(version == VERSION) { "unsupported backup version: $version" }+        var expectedIndex = 0+        while (true) {+            val length = readIntFrom(input) ?: break+            if (length <= 0 || length > MAX_SEGMENT_BLOB) throw IOException("invalid segment length: $length")+            val segment = ByteArray(length)+            if (fill(input, segment) != length) throw IOException("truncated segment")+            val plain = E2ee.aesDecrypt(masterKey, segment)+            if (plain.size < 4) throw IOException("corrupt segment")+            val index = readIntBE(plain, 0)+            if (index != expectedIndex) throw IOException("segment out of order: $index != $expectedIndex")+            output.write(plain, 4, plain.size - 4)+            expectedIndex+++        }+        output.flush()+    }++    fun encrypt(plain: ByteArray): ByteArray =+        ByteArrayOutputStream().also { encrypt(ByteArrayInputStream(plain), it) }.toByteArray()++    fun decrypt(blob: ByteArray): ByteArray =+        ByteArrayOutputStream().also { decrypt(ByteArrayInputStream(blob), it) }.toByteArray()++    companion object {+        const val VERSION = 1+        const val SEGMENT_SIZE = 1 shl 20 // 1 MiB plaintext per segment+        // Sanity bound so a corrupt length can't request a huge allocation.+        private const val MAX_SEGMENT_BLOB = SEGMENT_SIZE + 1024++        /** Reads exactly [buf].size bytes, or fewer at EOF; returns bytes read. */+        private fun fill(input: InputStream, buf: ByteArray): Int {+            var off = 0+            while (off < buf.size) {+                val r = input.read(buf, off, buf.size - off)+                if (r < 0) break+                off += r+            }+            return off+        }++        private fun writeIntBE(buf: ByteArray, offset: Int, value: Int) {+            buf[offset] = (value ushr 24).toByte()+            buf[offset + 1] = (value ushr 16).toByte()+            buf[offset + 2] = (value ushr 8).toByte()+            buf[offset + 3] = value.toByte()+        }++        private fun readIntBE(buf: ByteArray, offset: Int): Int =+            ((buf[offset].toInt() and 0xFF) shl 24) or+                ((buf[offset + 1].toInt() and 0xFF) shl 16) or+                ((buf[offset + 2].toInt() and 0xFF) shl 8) or+                (buf[offset + 3].toInt() and 0xFF)++        private fun writeIntTo(output: OutputStream, value: Int) {+            output.write(value ushr 24)+            output.write(value ushr 16)+            output.write(value ushr 8)+            output.write(value)+        }++        /** Reads a 4-byte BE int, or null at a clean EOF between segments. */+        private fun readIntFrom(input: InputStream): Int? {+            val b0 = input.read()+            if (b0 < 0) return null+            val b1 = input.read()+            val b2 = input.read()+            val b3 = input.read()+            if (b1 < 0 || b2 < 0 || b3 < 0) throw IOException("truncated segment header")+            return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3+        }+    }+}
backup/src/main/java/com/vayunmathur/backup/crypto/Hkdf.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/crypto/Hkdf.kt b/backup/src/main/java/com/vayunmathur/backup/crypto/Hkdf.ktnew file mode 100644index 0000000000..bfbb2367a7--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/crypto/Hkdf.kt@@ -0,0 +1,34 @@+package com.vayunmathur.backup.crypto++import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * HKDF (RFC 5869) over HMAC-SHA256, used to derive fixed-purpose sub-keys from the+ * BIP-0039 seed (e.g. the AES-256 master backup key) so a single recovery code+ * yields independent keys per use.+ */+object Hkdf {+    private const val HMAC = "HmacSHA256"+    private const val HASH_LEN = 32++    fun derive(ikm: ByteArray, info: ByteArray, length: Int, salt: ByteArray = ByteArray(HASH_LEN)): ByteArray {+        val prk = hmac(salt, ikm)+        val n = (length + HASH_LEN - 1) / HASH_LEN+        require(n <= 255) { "HKDF cannot derive more than 255 blocks" }+        val output = ByteArray(n * HASH_LEN)+        var previous = ByteArray(0)+        for (i in 1..n) {+            val mac = Mac.getInstance(HMAC).apply { init(SecretKeySpec(prk, HMAC)) }+            mac.update(previous)+            mac.update(info)+            mac.update(i.toByte())+            previous = mac.doFinal()+            previous.copyInto(output, (i - 1) * HASH_LEN)+        }+        return output.copyOf(length)+    }++    private fun hmac(key: ByteArray, data: ByteArray): ByteArray =+        Mac.getInstance(HMAC).apply { init(SecretKeySpec(key, HMAC)) }.doFinal(data)+}
backup/src/main/java/com/vayunmathur/backup/crypto/KeyManager.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/crypto/KeyManager.kt b/backup/src/main/java/com/vayunmathur/backup/crypto/KeyManager.ktnew file mode 100644index 0000000000..4497f8e624--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/crypto/KeyManager.kt@@ -0,0 +1,40 @@+package com.vayunmathur.backup.crypto++import android.content.Context+import android.util.Base64+import com.vayunmathur.library.util.DatabaseHelper++/**+ * Persists the AES-256 master backup key, wrapped by an AndroidKeyStore key, reusing+ * the repo's [DatabaseHelper] keystore pattern. The master key is derived from the+ * BIP-0039 seed via [Hkdf] so the twelve-word recovery code alone can reconstruct it+ * on a new device; here it is cached (keystore-wrapped) so routine backups don't+ * re-prompt for the code. An optional biometric gate can wrap this via+ * :library:biometric's BiometricDatabaseHelper.+ */+class KeyManager(context: Context) : DatabaseHelper(context) {+    override val keyStoreAlias = "backup_master_key"+    override val sharedPrefsName = "backup_secure_prefs"+    override val passphraseKey = "encrypted_master_key"+    override val ivKey = "master_key_iv"++    fun hasMasterKey(): Boolean = isKeyGenerated()++    /** Derives and persists the AES-256 master key from a BIP-0039 [seed]. */+    fun storeSeed(seed: ByteArray) {+        storePassphrase(Base64.encodeToString(deriveMasterKey(seed), Base64.NO_WRAP))+    }++    fun getMasterKey(): ByteArray = Base64.decode(getPassphrase(), Base64.NO_WRAP)++    fun clear() = deleteKey()++    companion object {+        private val MASTER_KEY_INFO =+            "com.vayunmathur.backup/master-key".toByteArray(Charsets.UTF_8)++        /** Derives the 32-byte AES-256 master key from a BIP-0039 seed. */+        fun deriveMasterKey(seed: ByteArray): ByteArray =+            Hkdf.derive(seed, MASTER_KEY_INFO, 32)+    }+}
backup/src/main/resources/bip39-english.txt
diff --git a/backup/src/main/resources/bip39-english.txt b/backup/src/main/resources/bip39-english.txtnew file mode 100644index 0000000000..942040ed50--- /dev/null+++ b/backup/src/main/resources/bip39-english.txt@@ -0,0 +1,2048 @@+abandon+ability+able+about+above+absent+absorb+abstract+absurd+abuse+access+accident+account+accuse+achieve+acid+acoustic+acquire+across+act+action+actor+actress+actual+adapt+add+addict+address+adjust+admit+adult+advance+advice+aerobic+affair+afford+afraid+again+age+agent+agree+ahead+aim+air+airport+aisle+alarm+album+alcohol+alert+alien+all+alley+allow+almost+alone+alpha+already+also+alter+always+amateur+amazing+among+amount+amused+analyst+anchor+ancient+anger+angle+angry+animal+ankle+announce+annual+another+answer+antenna+antique+anxiety+any+apart+apology+appear+apple+approve+april+arch+arctic+area+arena+argue+arm+armed+armor+army+around+arrange+arrest+arrive+arrow+art+artefact+artist+artwork+ask+aspect+assault+asset+assist+assume+asthma+athlete+atom+attack+attend+attitude+attract+auction+audit+august+aunt+author+auto+autumn+average+avocado+avoid+awake+aware+away+awesome+awful+awkward+axis+baby+bachelor+bacon+badge+bag+balance+balcony+ball+bamboo+banana+banner+bar+barely+bargain+barrel+base+basic+basket+battle+beach+bean+beauty+because+become+beef+before+begin+behave+behind+believe+below+belt+bench+benefit+best+betray+better+between+beyond+bicycle+bid+bike+bind+biology+bird+birth+bitter+black+blade+blame+blanket+blast+bleak+bless+blind+blood+blossom+blouse+blue+blur+blush+board+boat+body+boil+bomb+bone+bonus+book+boost+border+boring+borrow+boss+bottom+bounce+box+boy+bracket+brain+brand+brass+brave+bread+breeze+brick+bridge+brief+bright+bring+brisk+broccoli+broken+bronze+broom+brother+brown+brush+bubble+buddy+budget+buffalo+build+bulb+bulk+bullet+bundle+bunker+burden+burger+burst+bus+business+busy+butter+buyer+buzz+cabbage+cabin+cable+cactus+cage+cake+call+calm+camera+camp+can+canal+cancel+candy+cannon+canoe+canvas+canyon+capable+capital+captain+car+carbon+card+cargo+carpet+carry+cart+case+cash+casino+castle+casual+cat+catalog+catch+category+cattle+caught+cause+caution+cave+ceiling+celery+cement+census+century+cereal+certain+chair+chalk+champion+change+chaos+chapter+charge+chase+chat+cheap+check+cheese+chef+cherry+chest+chicken+chief+child+chimney+choice+choose+chronic+chuckle+chunk+churn+cigar+cinnamon+circle+citizen+city+civil+claim+clap+clarify+claw+clay+clean+clerk+clever+click+client+cliff+climb+clinic+clip+clock+clog+close+cloth+cloud+clown+club+clump+cluster+clutch+coach+coast+coconut+code+coffee+coil+coin+collect+color+column+combine+come+comfort+comic+common+company+concert+conduct+confirm+congress+connect+consider+control+convince+cook+cool+copper+copy+coral+core+corn+correct+cost+cotton+couch+country+couple+course+cousin+cover+coyote+crack+cradle+craft+cram+crane+crash+crater+crawl+crazy+cream+credit+creek+crew+cricket+crime+crisp+critic+crop+cross+crouch+crowd+crucial+cruel+cruise+crumble+crunch+crush+cry+crystal+cube+culture+cup+cupboard+curious+current+curtain+curve+cushion+custom+cute+cycle+dad+damage+damp+dance+danger+daring+dash+daughter+dawn+day+deal+debate+debris+decade+december+decide+decline+decorate+decrease+deer+defense+define+defy+degree+delay+deliver+demand+demise+denial+dentist+deny+depart+depend+deposit+depth+deputy+derive+describe+desert+design+desk+despair+destroy+detail+detect+develop+device+devote+diagram+dial+diamond+diary+dice+diesel+diet+differ+digital+dignity+dilemma+dinner+dinosaur+direct+dirt+disagree+discover+disease+dish+dismiss+disorder+display+distance+divert+divide+divorce+dizzy+doctor+document+dog+doll+dolphin+domain+donate+donkey+donor+door+dose+double+dove+draft+dragon+drama+drastic+draw+dream+dress+drift+drill+drink+drip+drive+drop+drum+dry+duck+dumb+dune+during+dust+dutch+duty+dwarf+dynamic+eager+eagle+early+earn+earth+easily+east+easy+echo+ecology+economy+edge+edit+educate+effort+egg+eight+either+elbow+elder+electric+elegant+element+elephant+elevator+elite+else+embark+embody+embrace+emerge+emotion+employ+empower+empty+enable+enact+end+endless+endorse+enemy+energy+enforce+engage+engine+enhance+enjoy+enlist+enough+enrich+enroll+ensure+enter+entire+entry+envelope+episode+equal+equip+era+erase+erode+erosion+error+erupt+escape+essay+essence+estate+eternal+ethics+evidence+evil+evoke+evolve+exact+example+excess+exchange+excite+exclude+excuse+execute+exercise+exhaust+exhibit+exile+exist+exit+exotic+expand+expect+expire+explain+expose+express+extend+extra+eye+eyebrow+fabric+face+faculty+fade+faint+faith+fall+false+fame+family+famous+fan+fancy+fantasy+farm+fashion+fat+fatal+father+fatigue+fault+favorite+feature+february+federal+fee+feed+feel+female+fence+festival+fetch+fever+few+fiber+fiction+field+figure+file+film+filter+final+find+fine+finger+finish+fire+firm+first+fiscal+fish+fit+fitness+fix+flag+flame+flash+flat+flavor+flee+flight+flip+float+flock+floor+flower+fluid+flush+fly+foam+focus+fog+foil+fold+follow+food+foot+force+forest+forget+fork+fortune+forum+forward+fossil+foster+found+fox+fragile+frame+frequent+fresh+friend+fringe+frog+front+frost+frown+frozen+fruit+fuel+fun+funny+furnace+fury+future+gadget+gain+galaxy+gallery+game+gap+garage+garbage+garden+garlic+garment+gas+gasp+gate+gather+gauge+gaze+general+genius+genre+gentle+genuine+gesture+ghost+giant+gift+giggle+ginger+giraffe+girl+give+glad+glance+glare+glass+glide+glimpse+globe+gloom+glory+glove+glow+glue+goat+goddess+gold+good+goose+gorilla+gospel+gossip+govern+gown+grab+grace+grain+grant+grape+grass+gravity+great+green+grid+grief+grit+grocery+group+grow+grunt+guard+guess+guide+guilt+guitar+gun+gym+habit+hair+half+hammer+hamster+hand+happy+harbor+hard+harsh+harvest+hat+have+hawk+hazard+head+health+heart+heavy+hedgehog+height+hello+helmet+help+hen+hero+hidden+high+hill+hint+hip+hire+history+hobby+hockey+hold+hole+holiday+hollow+home+honey+hood+hope+horn+horror+horse+hospital+host+hotel+hour+hover+hub+huge+human+humble+humor+hundred+hungry+hunt+hurdle+hurry+hurt+husband+hybrid+ice+icon+idea+identify+idle+ignore+ill+illegal+illness+image+imitate+immense+immune+impact+impose+improve+impulse+inch+include+income+increase+index+indicate+indoor+industry+infant+inflict+inform+inhale+inherit+initial+inject+injury+inmate+inner+innocent+input+inquiry+insane+insect+inside+inspire+install+intact+interest+into+invest+invite+involve+iron+island+isolate+issue+item+ivory+jacket+jaguar+jar+jazz+jealous+jeans+jelly+jewel+job+join+joke+journey+joy+judge+juice+jump+jungle+junior+junk+just+kangaroo+keen+keep+ketchup+key+kick+kid+kidney+kind+kingdom+kiss+kit+kitchen+kite+kitten+kiwi+knee+knife+knock+know+lab+label+labor+ladder+lady+lake+lamp+language+laptop+large+later+latin+laugh+laundry+lava+law+lawn+lawsuit+layer+lazy+leader+leaf+learn+leave+lecture+left+leg+legal+legend+leisure+lemon+lend+length+lens+leopard+lesson+letter+level+liar+liberty+library+license+life+lift+light+like+limb+limit+link+lion+liquid+list+little+live+lizard+load+loan+lobster+local+lock+logic+lonely+long+loop+lottery+loud+lounge+love+loyal+lucky+luggage+lumber+lunar+lunch+luxury+lyrics+machine+mad+magic+magnet+maid+mail+main+major+make+mammal+man+manage+mandate+mango+mansion+manual+maple+marble+march+margin+marine+market+marriage+mask+mass+master+match+material+math+matrix+matter+maximum+maze+meadow+mean+measure+meat+mechanic+medal+media+melody+melt+member+memory+mention+menu+mercy+merge+merit+merry+mesh+message+metal+method+middle+midnight+milk+million+mimic+mind+minimum+minor+minute+miracle+mirror+misery+miss+mistake+mix+mixed+mixture+mobile+model+modify+mom+moment+monitor+monkey+monster+month+moon+moral+more+morning+mosquito+mother+motion+motor+mountain+mouse+move+movie+much+muffin+mule+multiply+muscle+museum+mushroom+music+must+mutual+myself+mystery+myth+naive+name+napkin+narrow+nasty+nation+nature+near+neck+need+negative+neglect+neither+nephew+nerve+nest+net+network+neutral+never+news+next+nice+night+noble+noise+nominee+noodle+normal+north+nose+notable+note+nothing+notice+novel+now+nuclear+number+nurse+nut+oak+obey+object+oblige+obscure+observe+obtain+obvious+occur+ocean+october+odor+off+offer+office+often+oil+okay+old+olive+olympic+omit+once+one+onion+online+only+open+opera+opinion+oppose+option+orange+orbit+orchard+order+ordinary+organ+orient+original+orphan+ostrich+other+outdoor+outer+output+outside+oval+oven+over+own+owner+oxygen+oyster+ozone+pact+paddle+page+pair+palace+palm+panda+panel+panic+panther+paper+parade+parent+park+parrot+party+pass+patch+path+patient+patrol+pattern+pause+pave+payment+peace+peanut+pear+peasant+pelican+pen+penalty+pencil+people+pepper+perfect+permit+person+pet+phone+photo+phrase+physical+piano+picnic+picture+piece+pig+pigeon+pill+pilot+pink+pioneer+pipe+pistol+pitch+pizza+place+planet+plastic+plate+play+please+pledge+pluck+plug+plunge+poem+poet+point+polar+pole+police+pond+pony+pool+popular+portion+position+possible+post+potato+pottery+poverty+powder+power+practice+praise+predict+prefer+prepare+present+pretty+prevent+price+pride+primary+print+priority+prison+private+prize+problem+process+produce+profit+program+project+promote+proof+property+prosper+protect+proud+provide+public+pudding+pull+pulp+pulse+pumpkin+punch+pupil+puppy+purchase+purity+purpose+purse+push+put+puzzle+pyramid+quality+quantum+quarter+question+quick+quit+quiz+quote+rabbit+raccoon+race+rack+radar+radio+rail+rain+raise+rally+ramp+ranch+random+range+rapid+rare+rate+rather+raven+raw+razor+ready+real+reason+rebel+rebuild+recall+receive+recipe+record+recycle+reduce+reflect+reform+refuse+region+regret+regular+reject+relax+release+relief+rely+remain+remember+remind+remove+render+renew+rent+reopen+repair+repeat+replace+report+require+rescue+resemble+resist+resource+response+result+retire+retreat+return+reunion+reveal+review+reward+rhythm+rib+ribbon+rice+rich+ride+ridge+rifle+right+rigid+ring+riot+ripple+risk+ritual+rival+river+road+roast+robot+robust+rocket+romance+roof+rookie+room+rose+rotate+rough+round+route+royal+rubber+rude+rug+rule+run+runway+rural+sad+saddle+sadness+safe+sail+salad+salmon+salon+salt+salute+same+sample+sand+satisfy+satoshi+sauce+sausage+save+say+scale+scan+scare+scatter+scene+scheme+school+science+scissors+scorpion+scout+scrap+screen+script+scrub+sea+search+season+seat+second+secret+section+security+seed+seek+segment+select+sell+seminar+senior+sense+sentence+series+service+session+settle+setup+seven+shadow+shaft+shallow+share+shed+shell+sheriff+shield+shift+shine+ship+shiver+shock+shoe+shoot+shop+short+shoulder+shove+shrimp+shrug+shuffle+shy+sibling+sick+side+siege+sight+sign+silent+silk+silly+silver+similar+simple+since+sing+siren+sister+situate+six+size+skate+sketch+ski+skill+skin+skirt+skull+slab+slam+sleep+slender+slice+slide+slight+slim+slogan+slot+slow+slush+small+smart+smile+smoke+smooth+snack+snake+snap+sniff+snow+soap+soccer+social+sock+soda+soft+solar+soldier+solid+solution+solve+someone+song+soon+sorry+sort+soul+sound+soup+source+south+space+spare+spatial+spawn+speak+special+speed+spell+spend+sphere+spice+spider+spike+spin+spirit+split+spoil+sponsor+spoon+sport+spot+spray+spread+spring+spy+square+squeeze+squirrel+stable+stadium+staff+stage+stairs+stamp+stand+start+state+stay+steak+steel+stem+step+stereo+stick+still+sting+stock+stomach+stone+stool+story+stove+strategy+street+strike+strong+struggle+student+stuff+stumble+style+subject+submit+subway+success+such+sudden+suffer+sugar+suggest+suit+summer+sun+sunny+sunset+super+supply+supreme+sure+surface+surge+surprise+surround+survey+suspect+sustain+swallow+swamp+swap+swarm+swear+sweet+swift+swim+swing+switch+sword+symbol+symptom+syrup+system+table+tackle+tag+tail+talent+talk+tank+tape+target+task+taste+tattoo+taxi+teach+team+tell+ten+tenant+tennis+tent+term+test+text+thank+that+theme+then+theory+there+they+thing+this+thought+three+thrive+throw+thumb+thunder+ticket+tide+tiger+tilt+timber+time+tiny+tip+tired+tissue+title+toast+tobacco+today+toddler+toe+together+toilet+token+tomato+tomorrow+tone+tongue+tonight+tool+tooth+top+topic+topple+torch+tornado+tortoise+toss+total+tourist+toward+tower+town+toy+track+trade+traffic+tragic+train+transfer+trap+trash+travel+tray+treat+tree+trend+trial+tribe+trick+trigger+trim+trip+trophy+trouble+truck+true+truly+trumpet+trust+truth+try+tube+tuition+tumble+tuna+tunnel+turkey+turn+turtle+twelve+twenty+twice+twin+twist+two+type+typical+ugly+umbrella+unable+unaware+uncle+uncover+under+undo+unfair+unfold+unhappy+uniform+unique+unit+universe+unknown+unlock+until+unusual+unveil+update+upgrade+uphold+upon+upper+upset+urban+urge+usage+use+used+useful+useless+usual+utility+vacant+vacuum+vague+valid+valley+valve+van+vanish+vapor+various+vast+vault+vehicle+velvet+vendor+venture+venue+verb+verify+version+very+vessel+veteran+viable+vibrant+vicious+victory+video+view+village+vintage+violin+virtual+virus+visa+visit+visual+vital+vivid+vocal+voice+void+volcano+volume+vote+voyage+wage+wagon+wait+walk+wall+walnut+want+warfare+warm+warrior+wash+wasp+waste+water+wave+way+wealth+weapon+wear+weasel+weather+web+wedding+weekend+weird+welcome+west+wet+whale+what+wheat+wheel+when+where+whip+whisper+wide+width+wife+wild+will+win+window+wine+wing+wink+winner+winter+wire+wisdom+wise+wish+witness+wolf+woman+wonder+wood+wool+word+work+world+worry+worth+wrap+wreck+wrestle+wrist+write+wrong+yard+year+yellow+you+young+youth+zebra+zero+zone+zoo
backup/src/test/java/com/vayunmathur/backup/crypto/Bip39Test.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/crypto/Bip39Test.kt b/backup/src/test/java/com/vayunmathur/backup/crypto/Bip39Test.ktnew file mode 100644index 0000000000..bdba455fdb--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/crypto/Bip39Test.kt@@ -0,0 +1,101 @@+package com.vayunmathur.backup.crypto++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * BIP-0039 standard test vectors (Trezor reference vectors, passphrase "TREZOR")+ * plus round-trip and checksum-validation checks for [Bip39].+ */+class Bip39Test {+    private data class Vector(val entropyHex: String, val mnemonic: String, val seedHex: String)++    private val vectors = listOf(+        Vector(+            "00000000000000000000000000000000",+            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",+            "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",+        ),+        Vector(+            "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",+            "legal winner thank year wave sausage worth useful legal winner thank yellow",+            "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607",+        ),+        Vector(+            "80808080808080808080808080808080",+            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",+            "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8",+        ),+        Vector(+            "ffffffffffffffffffffffffffffffff",+            "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",+            "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069",+        ),+    )++    @Test+    fun wordListHas2048Words() {+        assertEquals(2048, Bip39.wordList.size)+        assertEquals("abandon", Bip39.wordList.first())+        assertEquals("zoo", Bip39.wordList.last())+    }++    @Test+    fun entropyToMnemonicMatchesVectors() {+        for (v in vectors) {+            assertEquals(v.mnemonic, Bip39.entropyToMnemonic(hex(v.entropyHex)).joinToString(" "))+        }+    }++    @Test+    fun mnemonicToEntropyMatchesVectors() {+        for (v in vectors) {+            assertContentEquals(hex(v.entropyHex), Bip39.mnemonicToEntropy(v.mnemonic.split(" ")))+        }+    }++    @Test+    fun mnemonicToSeedMatchesVectors() {+        for (v in vectors) {+            assertEquals(+                v.seedHex,+                Bip39.mnemonicToSeed(v.mnemonic.split(" "), "TREZOR").toHex(),+            )+        }+    }++    @Test+    fun generateProducesValidTwelveWordCode() {+        val code = Bip39.generate()+        assertEquals(Bip39.WORD_COUNT, code.size)+        assertTrue(Bip39.isValid(code))+        // Round-trips through entropy.+        assertContentEquals(+            Bip39.mnemonicToEntropy(code),+            Bip39.mnemonicToEntropy(Bip39.entropyToMnemonic(Bip39.mnemonicToEntropy(code))),+        )+    }++    @Test+    fun invalidChecksumIsRejected() {+        // Valid words, but not a valid checksum combination.+        val bad = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"+        assertFalse(Bip39.isValid(bad.split(" ")))+        assertFailsWith<IllegalArgumentException> { Bip39.mnemonicToEntropy(bad.split(" ")) }+    }++    @Test+    fun unknownWordIsRejected() {+        val bad = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon notaword"+        assertFailsWith<IllegalArgumentException> { Bip39.mnemonicToEntropy(bad.split(" ")) }+    }++    private fun hex(s: String): ByteArray =+        ByteArray(s.length / 2) { ((s[it * 2].digitToInt(16) shl 4) or s[it * 2 + 1].digitToInt(16)).toByte() }++    private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }+}
backup/src/test/java/com/vayunmathur/backup/crypto/CryptoTest.kt
diff --git a/backup/src/test/java/com/vayunmathur/backup/crypto/CryptoTest.kt b/backup/src/test/java/com/vayunmathur/backup/crypto/CryptoTest.ktnew file mode 100644index 0000000000..163f9d2738--- /dev/null+++ b/backup/src/test/java/com/vayunmathur/backup/crypto/CryptoTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.backup.crypto++import javax.crypto.AEADBadTagException+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse++/** Round-trip, multi-segment, and wrong-key/tamper checks for [Crypto]. */+class CryptoTest {+    private val key = ByteArray(32) { it.toByte() }+    private val otherKey = ByteArray(32) { (it + 1).toByte() }++    @Test+    fun roundTripSmallPayload() {+        val crypto = Crypto(key)+        val plain = "hello encrypted backup".toByteArray()+        assertContentEquals(plain, crypto.decrypt(crypto.encrypt(plain)))+    }++    @Test+    fun roundTripEmptyPayload() {+        val crypto = Crypto(key)+        assertContentEquals(ByteArray(0), crypto.decrypt(crypto.encrypt(ByteArray(0))))+    }++    @Test+    fun roundTripMultiSegmentPayload() {+        val crypto = Crypto(key)+        // Larger than one segment to exercise the framing + index sequencing.+        val plain = ByteArray(Crypto.SEGMENT_SIZE * 2 + 1234) { (it * 31).toByte() }+        assertContentEquals(plain, crypto.decrypt(crypto.encrypt(plain)))+    }++    @Test+    fun ciphertextDiffersFromPlaintext() {+        val crypto = Crypto(key)+        val plain = ByteArray(1000) { 7 }+        val blob = crypto.encrypt(plain)+        assertFalse(blob.copyOfRange(1, 1 + plain.size).contentEquals(plain))+    }++    @Test+    fun wrongKeyFailsToDecrypt() {+        val blob = Crypto(key).encrypt("secret".toByteArray())+        assertFailsWith<AEADBadTagException> { Crypto(otherKey).decrypt(blob) }+    }++    @Test+    fun tamperedSegmentFailsToDecrypt() {+        val crypto = Crypto(key)+        val blob = crypto.encrypt("secret payload".toByteArray())+        // Flip a byte inside the first segment's ciphertext (past version + length header).+        blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0xFF).toByte()+        assertFailsWith<AEADBadTagException> { crypto.decrypt(blob) }+    }++    @Test+    fun versionByteIsWritten() {+        val blob = Crypto(key).encrypt("x".toByteArray())+        assertEquals(Crypto.VERSION, blob[0].toInt())+    }++    @Test+    fun rejectsNon32ByteKey() {+        assertFailsWith<IllegalArgumentException> { Crypto(ByteArray(16)) }+    }+}