RecoveryWords.kt

6.0 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    // Mask to a byte before the unsigned shift: a Byte >= 0x80 sign-extends to a18    // negative Int, so `toInt() ushr 4` would yield a 28-bit value, not the 4-bit19    // checksum. The browser reads a Uint8 (`recovery-words.ts:36`). Without the20    // mask, ~50% of root keys (SHA[0] >= 0x80) produce non-browser-parity words.21    val checksum = (entropyHash[0].toInt() and 0xff) ushr 42223    var bitsBig = BigInteger.ZERO24    for (i in 0 until 16) {25        bitsBig = bitsBig.shiftLeft(8).or(BigInteger.valueOf((rootKeyBytes[i].toInt() and 0xff).toLong()))26    }27    bitsBig = bitsBig.shiftLeft(4).or(BigInteger.valueOf(checksum.toLong()))2829    val words = ArrayList<String>(TOTAL_WORDS)30    for (i in 0 until TOTAL_WORDS) {31        val shift = (TOTAL_WORDS - 1 - i) * WORD_BITS32        val index = bitsBig.shiftRight(shift).and(BigInteger.valueOf(0x7ffL)).toInt()33        words += WORD_LIST[index]34    }35    return words36}3738fun wordsToRootKeyMaterial(words: List<String>): ByteArray {39    require(words.size == TOTAL_WORDS) { "exactly $TOTAL_WORDS words required" }4041    val indices = IntArray(words.size)42    for (i in words.indices) {43        val word = words[i].trim().lowercase()44        val index = WORD_LIST.indexOf(word)45        require(index >= 0) { "unknown word at position ${i + 1}: \"${words[i]}\"" }46        indices[i] = index47    }4849    var bitsBig = BigInteger.ZERO50    for (index in indices) {51        bitsBig = bitsBig.shiftLeft(WORD_BITS).or(BigInteger.valueOf(index.toLong()))52    }5354    val entropy = ByteArray(16)55    for (i in 0 until 16) {56        val byteShift = 124 - i * 857        entropy[i] = bitsBig.shiftRight(byteShift).and(BigInteger.valueOf(0xffL)).toByte()58    }5960    val storedChecksum = bitsBig.and(BigInteger.valueOf(0xFL)).toInt()61    val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy)62    // See rootKeyToWords: mask to a byte before the unsigned shift (browser parity).63    val computedChecksum = (entropyHash[0].toInt() and 0xff) ushr 464    require(storedChecksum == computedChecksum) { "invalid recovery words — checksum mismatch" }6566    return ByteArray(32).also { it.fill(0); System.arraycopy(entropy, 0, it, 0, entropy.size) }67}6869/**70 * Generate a random 32-byte root key whose recovery words round-trip cleanly.71 *72 * WORD_LIST carries "abandon" at both index 0 and 1 (a byte-identical parity copy73 * of the browser list), so `wordsToRootKeyMaterial` — which reconstructs entropy74 * via `indexOf` — cannot invert any phrase that `rootKeyToWords` emitted from75 * index 1; it throws on the checksum. The browser's `createVault` (`vault.ts:947`)76 * does NOT retry and therefore throws for those ~0.6% of root keys (a latent77 * reference bug). We deviate deliberately and safely: regenerate until the words78 * round-trip, yielding a strict, fully cross-compatible SUBSET of root keys. Any79 * vault created this way is recoverable by the browser too.80 */81fun generateRecoverableRootKey(maxAttempts: Int = 64): ByteArray {82    val rng = java.security.SecureRandom()83    repeat(maxAttempts) {84        val candidate = ByteArray(32).also(rng::nextBytes)85        val words = rootKeyToWords(candidate)86        val roundTrips = runCatching { wordsToRootKeyMaterial(words) }.isSuccess87        if (roundTrips) return candidate88        candidate.fill(0)89    }90    // Astronomically unlikely (P(fail)^64 with P(fail)≈0.006). Surface rather than91    // ship a root key whose displayed words cannot be entered back.92    throw IllegalStateException("could not generate a round-tripping root key")93}9495/** Lowercase, unseparated hex of [bytes] — the exact ASCII the browser wraps in the escrow. */96fun rootKeyToHex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }9798/** Inverse of [rootKeyToHex]; tolerant of upper/lower case. */99fun hexToRootKey(hex: String): ByteArray {100    require(hex.length % 2 == 0) { "odd-length hex" }101    return ByteArray(hex.length / 2) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() }102}103104fun deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec {105    val generator = HKDFBytesGenerator(SHA256Digest())106    generator.init(HKDFParameters(wordMaterial, salt, "peach-recovery-v1".encodeToByteArray()))107    val out = ByteArray(32)108    generator.generateBytes(out, 0, out.size)109    return SecretKeySpec(out, "AES")110}111112fun findInvalidWords(words: List<String>): List<Pair<Int, String>> {113    val invalid = ArrayList<Pair<Int, String>>()114    for (i in words.indices) {115        val w = words[i].trim().lowercase()116        if (w.isBlank() || WORD_LIST.indexOf(w) == -1) {117            invalid += i to words[i]118        }119    }120    return invalid121}122123fun getWordSuggestions(prefix: String, maxResults: Int = 5): List<String> {124    val p = prefix.trim().lowercase()125    if (p.length < 2) return emptyList()126    return WORD_LIST.filter { it.startsWith(p) }.take(maxResults)127}128129/**130 * BLAKE3 hash (hex) of the space-joined, trimmed, lowercased recovery words.131 * Stored in vault metadata so recovery-word entry can be verified without132 * persisting the words. Mirrors the browser's recovery-hash derivation.133 */134fun recoveryWordsHash(words: List<String>): String {135    val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()136    val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)137    digest.update(canonical, 0, canonical.size)138    val out = ByteArray(32)139    digest.doFinal(out, 0)140    return out.joinToString("") { "%02x".format(it) }141}