VaultCrypto.kt

6.7 KB · raw

1package com.peachpasswords.vault23import org.bouncycastle.crypto.generators.Argon2BytesGenerator4import org.bouncycastle.crypto.params.Argon2Parameters5import java.security.SecureRandom6import java.text.Normalizer7import javax.crypto.Cipher8import javax.crypto.spec.GCMParameterSpec9import javax.crypto.spec.SecretKeySpec1011object VaultCrypto {12    const val ARGON2_MEMORY_KB = 6553613    const val ARGON2_ITERATIONS = 314    const val ARGON2_PARALLELISM = 415    const val ARGON2_HASH_LENGTH = 3216    const val SALT_SIZE = 1617    const val NONCE_SIZE = 1218    const val TAG_LENGTH_BITS = 12819    const val KEY_SIZE = 3220    const val PAD_BLOCK = 102421    const val DURESS_SLOT_SIZE = 262_1442223    val PADDING_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)24    private const val LARGE_PADDING_STEP = 65_5362526    const val AAD_SLOT_A = "slot_a_v1"27    const val AAD_SLOT_B = "slot_b_v1"28    const val AAD_ROOT_KEY = "pw_root_v1"2930    /**31     * Distinct from [AAD_SLOT_A] so a recovery-escrow blob can never be swapped in32     * as a slot-A blob (GCM auth covers the AAD). Used by Android's whole-payload33     * offline-restore escrow.34     */35    const val AAD_RECOVERY = "recovery_escrow_v1"3637    /**38     * AAD for the browser-byte-compatible root-key escrow. The browser wraps the39     * 32-byte root key under AAD = the single byte 0x01 (`vault.ts:298`); matching40     * it byte-for-byte is what lets the same 12 words unwrap the same root key on41     * either platform. Do NOT change — it is a cross-platform wire constant.42     */43    val AAD_RECOVERY_ROOTKEY = byteArrayOf(1)4445    private val secureRandom = SecureRandom()46    private var _lastTimestamp = 0L4748    /**49     * MF-4 / LV-1: NFC-normalize the password, then hash explicit UTF-8 bytes —50     * byte-for-byte identical to the browser's `password.normalize("NFC")` fed51     * to Argon2id (`argon2.ts` deriveKey). NFC normalization makes a visually52     * identical password typed in a different normalization form (NFD on macOS53     * dead-keys, some IMEs) derive the same key on every platform. UTF-8 (not54     * BouncyCastle's per-UTF-16-unit char[] path) keeps non-BMP characters55     * (emoji, surrogate pairs) consistent across platforms.56     */57    fun deriveKey(password: String, salt: ByteArray): ByteArray =58        deriveKeyFromBytes(59            Normalizer.normalize(password, Normalizer.Form.NFC).toByteArray(Charsets.UTF_8),60            salt,61        )6263    /**64     * LV-1 legacy fallback ONLY: derive WITHOUT NFC normalization (raw UTF-865     * bytes), for unlocking a vault sealed before normalization existed with a66     * non-NFC password. Every normal path uses [deriveKey].67     */68    fun deriveKeyRaw(password: String, salt: ByteArray): ByteArray =69        deriveKeyFromBytes(password.toByteArray(Charsets.UTF_8), salt)7071    private fun deriveKeyFromBytes(passwordBytes: ByteArray, salt: ByteArray): ByteArray {72        val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)73            .withSalt(salt)74            .withParallelism(ARGON2_PARALLELISM)75            .withMemoryAsKB(ARGON2_MEMORY_KB)76            .withIterations(ARGON2_ITERATIONS)77            .build()78        val generator = Argon2BytesGenerator().apply { init(params) }79        val hash = ByteArray(ARGON2_HASH_LENGTH)80        try {81            generator.generateBytes(passwordBytes, hash)82        } finally {83            // Zero the transient password bytes immediately after use.84            passwordBytes.fill(0)85        }86        return hash87    }8889    fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray =90        encrypt(plaintext, key, aad.toByteArray(Charsets.UTF_8))9192    fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray =93        decrypt(data, key, aad.toByteArray(Charsets.UTF_8))9495    /**96     * Raw-AAD encrypt. Output is `nonce(12) || ciphertext || tag(16)`. The97     * [aad] bytes are authenticated, not encrypted. Used for the root-key98     * escrow whose AAD is the browser's single 0x01 byte ([AAD_RECOVERY_ROOTKEY]).99     */100    fun encrypt(plaintext: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {101        val nonce = ByteArray(NONCE_SIZE).also(secureRandom::nextBytes)102        val cipher = Cipher.getInstance("AES/GCM/NoPadding")103        cipher.init(104            Cipher.ENCRYPT_MODE,105            SecretKeySpec(key, "AES"),106            GCMParameterSpec(TAG_LENGTH_BITS, nonce),107        )108        cipher.updateAAD(aad)109        return nonce + cipher.doFinal(plaintext)110    }111112    fun decrypt(data: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {113        require(data.size >= NONCE_SIZE) { "Data too short" }114        val nonce = data.copyOfRange(0, NONCE_SIZE)115        val ciphertext = data.copyOfRange(NONCE_SIZE, data.size)116        val cipher = Cipher.getInstance("AES/GCM/NoPadding")117        cipher.init(118            Cipher.DECRYPT_MODE,119            SecretKeySpec(key, "AES"),120            GCMParameterSpec(TAG_LENGTH_BITS, nonce),121        )122        cipher.updateAAD(aad)123        return cipher.doFinal(ciphertext)124    }125126    fun generateSalt(): ByteArray = ByteArray(SALT_SIZE).also(secureRandom::nextBytes)127    fun generateRootKey(): ByteArray = ByteArray(KEY_SIZE).also(secureRandom::nextBytes)128    fun generateNoise(): ByteArray = ByteArray(DURESS_SLOT_SIZE).also(secureRandom::nextBytes)129130    fun padToBucket(data: ByteArray): ByteArray {131        val target = PADDING_BUCKETS.firstOrNull { it >= data.size }?.toLong()132            ?: run {133                val size = data.size.toLong()134                val remainder = size % LARGE_PADDING_STEP135                size + if (remainder == 0L) 0L else LARGE_PADDING_STEP - remainder136            }137        require(target <= Int.MAX_VALUE) { "padded plaintext is too large" }138        return data.copyOf(target.toInt())139    }140141    fun padToBlock(data: ByteArray): ByteArray {142        val remainder = data.size % PAD_BLOCK143        if (remainder == 0) return data144        return data.copyOf(data.size + (PAD_BLOCK - remainder))145    }146147    @Synchronized148    fun monotonicEntryTimestamp(currentModifiedAt: Long? = null): Long {149        val base = maxOf(System.currentTimeMillis(), (currentModifiedAt ?: 0L) + 1L, _lastTimestamp + 1L)150        _lastTimestamp = base151        return base152    }153154    /**155     * Reset the process-global monotonic entry clock. TEST ONLY.156     *157     * [monotonicEntryTimestamp] never moves backwards, so any test that feeds158     * it a far-future baseline leaves every later test in the same JVM issuing159     * far-future timestamps. That is invisible until something compares against160     * a clock-skew bound — [SyncLimits.clampSyncTimestamp] does, and a local161     * entry stamped beyond the skew window silently strands remote tombstones.162     */163    fun resetMonotonicClockForTest() {164        _lastTimestamp = 0L165    }166167    fun zero(bytes: ByteArray) {168        bytes.fill(0)169    }170}