Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / PqcIdentity.kt
PqcIdentity.kt117 lines · 5.6 KiBRaw
| 1 | package com.vayunmathur.e2ee |
| 2 | |
| 3 | import kotlinx.coroutines.sync.Mutex |
| 4 | import kotlinx.coroutines.sync.withLock |
| 5 | |
| 6 | /** |
| 7 | * A device's post-quantum identity for the Office app: an ML-KEM keypair (encryption) plus an |
| 8 | * ML-DSA keypair (signatures), persisted via an [E2eeKeyStore]. Keys are stored/handled as DER |
| 9 | * (byte-compatible with the previous Bouncy Castle encoding). Private keys never leave the device; |
| 10 | * [publicBundle] (both public keys) is what gets registered in the directory / used to encrypt to you. |
| 11 | */ |
| 12 | class PqcIdentity internal constructor( |
| 13 | val publicBundle: ByteArray, |
| 14 | private val kemPrivate: ByteArray, |
| 15 | private val dsaPrivate: ByteArray, |
| 16 | ) { |
| 17 | /** Decrypts data encrypted to this identity via [Pqc.encryptTo]. */ |
| 18 | fun decrypt(ciphertext: ByteArray): ByteArray = Pqc.decrypt(kemPrivate, ciphertext) |
| 19 | |
| 20 | /** Signs data with this identity's ML-DSA key. */ |
| 21 | fun sign(data: ByteArray): ByteArray = Pqc.signWith(dsaPrivate, data) |
| 22 | |
| 23 | /** |
| 24 | * True only if each private half matches the public half in [publicBundle]. Persisted |
| 25 | * halves are individual store entries, so a partial write (crash mid-store, a store that |
| 26 | * kept only some entries) or interleaved concurrent stores can leave two halves from |
| 27 | * different generations side by side; presence of all four entries alone does not prove |
| 28 | * they belong together. The probes stay on-device: an encrypt/decrypt round-trip for the |
| 29 | * KEM pair and a sign/verify round-trip for the DSA pair. |
| 30 | */ |
| 31 | private fun pairsConsistent(): Boolean = runCatching { |
| 32 | val kemProbe = KEM_PROBE.encodeToByteArray() |
| 33 | val encrypted = Pqc.encryptTo(publicBundle, kemProbe) |
| 34 | if (!decrypt(encrypted).contentEquals(kemProbe)) return@runCatching false |
| 35 | val dsaProbe = DSA_PROBE.encodeToByteArray() |
| 36 | Pqc.verify(publicBundle, dsaProbe, sign(dsaProbe)) |
| 37 | }.getOrDefault(false) |
| 38 | |
| 39 | /** Loading and generation entry points for [PqcIdentity]. */ |
| 40 | companion object { |
| 41 | private const val KEM_PROBE = "pqc-identity-kem-pair-check-v1" |
| 42 | private const val DSA_PROBE = "pqc-identity-dsa-pair-check-v1" |
| 43 | private const val MAX_LOAD_ATTEMPTS = 3 |
| 44 | |
| 45 | private val loadMutex = Mutex() |
| 46 | |
| 47 | /** |
| 48 | * Loads the persisted PQC keypairs, generating + storing them on first use. |
| 49 | * |
| 50 | * A persisted set is used only when it is complete and both pairs verify against |
| 51 | * each other (see [pairsConsistent]). An incomplete or mismatched set is replaced |
| 52 | * wholesale: keeping any surviving half and pairing it with a freshly generated |
| 53 | * other half would publish a bundle whose private half belongs to a different |
| 54 | * keypair, so nothing encrypted to it could ever be decrypted. First creation on an |
| 55 | * empty store writes with `onlyIfAbsent` and re-reads the persisted winner; in-process |
| 56 | * callers are serialised by [loadMutex], and a re-read that still fails the pair |
| 57 | * check is overwritten on the next attempt rather than returned. |
| 58 | */ |
| 59 | suspend fun loadOrCreate(store: E2eeKeyStore, prefix: String = "pqc"): PqcIdentity = |
| 60 | loadMutex.withLock { |
| 61 | var result: PqcIdentity? = null |
| 62 | var attempt = 0 |
| 63 | while (result == null && attempt < MAX_LOAD_ATTEMPTS) { |
| 64 | attempt++ |
| 65 | val keys = readKeys(store, prefix) |
| 66 | val persisted = keys.toIdentityOrNull() |
| 67 | if (persisted != null && persisted.pairsConsistent()) { |
| 68 | result = persisted |
| 69 | } else { |
| 70 | generateAndStore(store, prefix, overwrite = keys.hasAny) |
| 71 | val stored = readKeys(store, prefix).toIdentityOrNull() |
| 72 | if (stored != null && stored.pairsConsistent()) result = stored |
| 73 | } |
| 74 | } |
| 75 | result ?: error("PQC identity store returned no consistent keys") |
| 76 | } |
| 77 | |
| 78 | private suspend fun readKeys(store: E2eeKeyStore, prefix: String): PqcKeys = PqcKeys( |
| 79 | kemPub = store.getBytes("${prefix}KemPub"), |
| 80 | kemPriv = store.getBytes("${prefix}KemPriv"), |
| 81 | dsaPub = store.getBytes("${prefix}DsaPub"), |
| 82 | dsaPriv = store.getBytes("${prefix}DsaPriv") |
| 83 | ) |
| 84 | |
| 85 | private data class PqcKeys( |
| 86 | val kemPub: ByteArray?, |
| 87 | val kemPriv: ByteArray?, |
| 88 | val dsaPub: ByteArray?, |
| 89 | val dsaPriv: ByteArray? |
| 90 | ) { |
| 91 | val hasAny: Boolean |
| 92 | get() = kemPub != null || kemPriv != null || dsaPub != null || dsaPriv != null |
| 93 | |
| 94 | private val isComplete: Boolean |
| 95 | get() = kemPub != null && kemPriv != null && dsaPub != null && dsaPriv != null |
| 96 | |
| 97 | fun toIdentityOrNull(): PqcIdentity? { |
| 98 | if (!isComplete) return null |
| 99 | return PqcIdentity( |
| 100 | Pqc.bundle(kemPub!!, dsaPub!!), |
| 101 | kemPriv!!, |
| 102 | dsaPriv!! |
| 103 | ) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | private suspend fun generateAndStore(store: E2eeKeyStore, prefix: String, overwrite: Boolean) { |
| 108 | val (kemPubNew, kemPrivNew) = Pqc.generateKem() |
| 109 | val (dsaPubNew, dsaPrivNew) = Pqc.generateDsa() |
| 110 | val onlyIfAbsent = !overwrite |
| 111 | store.setBytes("${prefix}KemPub", kemPubNew, onlyIfAbsent = onlyIfAbsent) |
| 112 | store.setBytes("${prefix}KemPriv", kemPrivNew, onlyIfAbsent = onlyIfAbsent) |
| 113 | store.setBytes("${prefix}DsaPub", dsaPubNew, onlyIfAbsent = onlyIfAbsent) |
| 114 | store.setBytes("${prefix}DsaPriv", dsaPrivNew, onlyIfAbsent = onlyIfAbsent) |
| 115 | } |
| 116 | } |
| 117 | } |