RecoveryWords.kt

4.8 KB · raw

1package com.peachpasswords.vault23import org.bouncycastle.crypto.generators.HKDFBytesGenerator4import org.bouncycastle.crypto.digests.SHA256Digest5import org.bouncycastle.crypto.params.HKDFParameters6import java.math.BigInteger7import java.security.MessageDigest8import javax.crypto.spec.SecretKeySpec910private const val WORD_BITS = 1111private const val TOTAL_WORDS = 121213fun rootKeyToWords(rootKeyBytes: ByteArray): List<String> {14    require(rootKeyBytes.size == 32) { "root key must be 32 bytes" }15    val entropy16 = rootKeyBytes.copyOfRange(0, 16)16    val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy16)17    val checksum = entropyHash[0].toInt() ushr 41819    var bitsBig = BigInteger.ZERO20    for (i in 0 until 16) {21        bitsBig = bitsBig.shiftLeft(8).or(BigInteger.valueOf((rootKeyBytes[i].toInt() and 0xff).toLong()))22    }23    bitsBig = bitsBig.shiftLeft(4).or(BigInteger.valueOf(checksum.toLong()))2425    val words = ArrayList<String>(TOTAL_WORDS)26    for (i in 0 until TOTAL_WORDS) {27        val shift = (TOTAL_WORDS - 1 - i) * WORD_BITS28        val index = bitsBig.shiftRight(shift).and(BigInteger.valueOf(0x7ffL)).toInt()29        words += WORD_LIST[index]30    }31    return words32}3334fun wordsToRootKeyMaterial(words: List<String>): ByteArray {35    require(words.size == TOTAL_WORDS) { "exactly $TOTAL_WORDS words required" }3637    val indices = IntArray(words.size)38    for (i in words.indices) {39        val word = words[i].trim().lowercase()40        val index = WORD_LIST.indexOf(word)41        require(index >= 0) { "unknown word at position ${i + 1}: \"${words[i]}\"" }42        indices[i] = index43    }4445    var bitsBig = BigInteger.ZERO46    for (index in indices) {47        bitsBig = bitsBig.shiftLeft(WORD_BITS).or(BigInteger.valueOf(index.toLong()))48    }4950    val entropy = ByteArray(16)51    for (i in 0 until 16) {52        val byteShift = 124 - i * 853        entropy[i] = bitsBig.shiftRight(byteShift).and(BigInteger.valueOf(0xffL)).toByte()54    }5556    val storedChecksum = bitsBig.and(BigInteger.valueOf(0xFL)).toInt()57    val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy)58    val computedChecksum = entropyHash[0].toInt() ushr 459    require(storedChecksum == computedChecksum) { "invalid recovery words — checksum mismatch" }6061    return ByteArray(32).also { it.fill(0); System.arraycopy(entropy, 0, it, 0, entropy.size) }62}6364/**65 * Collision-stable key material for the recovery escrow, derived from the canonical66 * word *strings* rather than reconstructed entropy indices.67 *68 * WORD_LIST carries "abandon" at both index 0 and 1 (a deliberate parity copy of69 * the browser list), so `wordsToRootKeyMaterial` — which reconstructs entropy via70 * `indexOf` — is NOT a perfect inverse of `rootKeyToWords` for any phrase that uses71 * index 1: the words become ambiguous. The escrow must round-trip for EVERY vault,72 * so it keys off BLAKE3 of the space-joined words (the same canonical form73 * [recoveryWordsHash] verifies), which is identical whichever "abandon" index the74 * phrase was generated from.75 */76fun wordKeyMaterial(words: List<String>): ByteArray {77    val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()78    val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)79    digest.update(canonical, 0, canonical.size)80    val out = ByteArray(32)81    digest.doFinal(out, 0)82    return out83}8485fun deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec {86    val generator = HKDFBytesGenerator(SHA256Digest())87    generator.init(HKDFParameters(wordMaterial, salt, "peach-recovery-v1".encodeToByteArray()))88    val out = ByteArray(32)89    generator.generateBytes(out, 0, out.size)90    return SecretKeySpec(out, "AES")91}9293fun findInvalidWords(words: List<String>): List<Pair<Int, String>> {94    val invalid = ArrayList<Pair<Int, String>>()95    for (i in words.indices) {96        val w = words[i].trim().lowercase()97        if (w.isBlank() || WORD_LIST.indexOf(w) == -1) {98            invalid += i to words[i]99        }100    }101    return invalid102}103104fun getWordSuggestions(prefix: String, maxResults: Int = 5): List<String> {105    val p = prefix.trim().lowercase()106    if (p.length < 2) return emptyList()107    return WORD_LIST.filter { it.startsWith(p) }.take(maxResults)108}109110/**111 * BLAKE3 hash (hex) of the space-joined, trimmed, lowercased recovery words.112 * Stored in vault metadata so recovery-word entry can be verified without113 * persisting the words. Mirrors the browser's recovery-hash derivation.114 */115fun recoveryWordsHash(words: List<String>): String {116    val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()117    val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)118    digest.update(canonical, 0, canonical.size)119    val out = ByteArray(32)120    digest.doFinal(out, 0)121    return out.joinToString("") { "%02x".format(it) }122}