package com.vayunmathur.e2ee import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** * A device's post-quantum identity for the Office app: an ML-KEM keypair (encryption) plus an * ML-DSA keypair (signatures), persisted via an [E2eeKeyStore]. Keys are stored/handled as DER * (byte-compatible with the previous Bouncy Castle encoding). Private keys never leave the device; * [publicBundle] (both public keys) is what gets registered in the directory / used to encrypt to you. */ class PqcIdentity internal constructor( val publicBundle: ByteArray, private val kemPrivate: ByteArray, private val dsaPrivate: ByteArray, ) { /** Decrypts data encrypted to this identity via [Pqc.encryptTo]. */ fun decrypt(ciphertext: ByteArray): ByteArray = Pqc.decrypt(kemPrivate, ciphertext) /** Signs data with this identity's ML-DSA key. */ fun sign(data: ByteArray): ByteArray = Pqc.signWith(dsaPrivate, data) /** * True only if each private half matches the public half in [publicBundle]. Persisted * halves are individual store entries, so a partial write (crash mid-store, a store that * kept only some entries) or interleaved concurrent stores can leave two halves from * different generations side by side; presence of all four entries alone does not prove * they belong together. The probes stay on-device: an encrypt/decrypt round-trip for the * KEM pair and a sign/verify round-trip for the DSA pair. */ private fun pairsConsistent(): Boolean = runCatching { val kemProbe = KEM_PROBE.encodeToByteArray() val encrypted = Pqc.encryptTo(publicBundle, kemProbe) if (!decrypt(encrypted).contentEquals(kemProbe)) return@runCatching false val dsaProbe = DSA_PROBE.encodeToByteArray() Pqc.verify(publicBundle, dsaProbe, sign(dsaProbe)) }.getOrDefault(false) /** Loading and generation entry points for [PqcIdentity]. */ companion object { private const val KEM_PROBE = "pqc-identity-kem-pair-check-v1" private const val DSA_PROBE = "pqc-identity-dsa-pair-check-v1" private const val MAX_LOAD_ATTEMPTS = 3 private val loadMutex = Mutex() /** * Loads the persisted PQC keypairs, generating + storing them on first use. * * A persisted set is used only when it is complete and both pairs verify against * each other (see [pairsConsistent]). An incomplete or mismatched set is replaced * wholesale: keeping any surviving half and pairing it with a freshly generated * other half would publish a bundle whose private half belongs to a different * keypair, so nothing encrypted to it could ever be decrypted. First creation on an * empty store writes with `onlyIfAbsent` and re-reads the persisted winner; in-process * callers are serialised by [loadMutex], and a re-read that still fails the pair * check is overwritten on the next attempt rather than returned. */ suspend fun loadOrCreate(store: E2eeKeyStore, prefix: String = "pqc"): PqcIdentity = loadMutex.withLock { var result: PqcIdentity? = null var attempt = 0 while (result == null && attempt < MAX_LOAD_ATTEMPTS) { attempt++ val keys = readKeys(store, prefix) val persisted = keys.toIdentityOrNull() if (persisted != null && persisted.pairsConsistent()) { result = persisted } else { generateAndStore(store, prefix, overwrite = keys.hasAny) val stored = readKeys(store, prefix).toIdentityOrNull() if (stored != null && stored.pairsConsistent()) result = stored } } result ?: error("PQC identity store returned no consistent keys") } private suspend fun readKeys(store: E2eeKeyStore, prefix: String): PqcKeys = PqcKeys( kemPub = store.getBytes("${prefix}KemPub"), kemPriv = store.getBytes("${prefix}KemPriv"), dsaPub = store.getBytes("${prefix}DsaPub"), dsaPriv = store.getBytes("${prefix}DsaPriv") ) private data class PqcKeys( val kemPub: ByteArray?, val kemPriv: ByteArray?, val dsaPub: ByteArray?, val dsaPriv: ByteArray? ) { val hasAny: Boolean get() = kemPub != null || kemPriv != null || dsaPub != null || dsaPriv != null private val isComplete: Boolean get() = kemPub != null && kemPriv != null && dsaPub != null && dsaPriv != null fun toIdentityOrNull(): PqcIdentity? { if (!isComplete) return null return PqcIdentity( Pqc.bundle(kemPub!!, dsaPub!!), kemPriv!!, dsaPriv!! ) } } private suspend fun generateAndStore(store: E2eeKeyStore, prefix: String, overwrite: Boolean) { val (kemPubNew, kemPrivNew) = Pqc.generateKem() val (dsaPubNew, dsaPrivNew) = Pqc.generateDsa() val onlyIfAbsent = !overwrite store.setBytes("${prefix}KemPub", kemPubNew, onlyIfAbsent = onlyIfAbsent) store.setBytes("${prefix}KemPriv", kemPrivNew, onlyIfAbsent = onlyIfAbsent) store.setBytes("${prefix}DsaPub", dsaPubNew, onlyIfAbsent = onlyIfAbsent) store.setBytes("${prefix}DsaPriv", dsaPrivNew, onlyIfAbsent = onlyIfAbsent) } } }