Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / PqcIdentity.kt

PqcIdentity.kt70 lines · 3.0 KiBRaw
1package com.vayunmathur.e2ee
2
3/**
4 * A device's post-quantum identity for the Office app: an ML-KEM keypair (encryption) plus an
5 * ML-DSA keypair (signatures), persisted via an [E2eeKeyStore]. Keys are stored/handled as DER
6 * (byte-compatible with the previous Bouncy Castle encoding). Private keys never leave the device;
7 * [publicBundle] (both public keys) is what gets registered in the directory / used to encrypt to you.
8 */
9class PqcIdentity internal constructor(
10 val publicBundle: ByteArray,
11 private val kemPrivate: ByteArray,
12 private val dsaPrivate: ByteArray,
13) {
14 /** Decrypts data encrypted to this identity via [Pqc.encryptTo]. */
15 fun decrypt(ciphertext: ByteArray): ByteArray = Pqc.decrypt(kemPrivate, ciphertext)
16
17 /** Signs data with this identity's ML-DSA key. */
18 fun sign(data: ByteArray): ByteArray = Pqc.signWith(dsaPrivate, data)
19
20 companion object {
21 /**
22 * Loads the persisted PQC keypairs, generating + storing them on first use.
23 * Fixed race: re-read final persisted values after `onlyIfAbsent` stores
24 * to avoid returning an ephemeral identity that would fail to decrypt.
25 */
26 suspend fun loadOrCreate(store: E2eeKeyStore, prefix: String = "pqc"): PqcIdentity {
27 readPersisted(store, prefix)?.let { return it }
28 generateAndStore(store, prefix)
29 // Re-read final persisted (winner of concurrent race).
30 return readPersisted(store, prefix) ?: error("PQC identity store returned no keys")
31 }
32
33 private suspend fun readPersisted(store: E2eeKeyStore, prefix: String): PqcIdentity? {
34 val keys = PqcKeys(
35 kemPub = store.getBytes("${prefix}KemPub"),
36 kemPriv = store.getBytes("${prefix}KemPriv"),
37 dsaPub = store.getBytes("${prefix}DsaPub"),
38 dsaPriv = store.getBytes("${prefix}DsaPriv")
39 )
40 if (!keys.isComplete) return null
41 return PqcIdentity(
42 Pqc.bundle(keys.kemPub!!, keys.dsaPub!!),
43 keys.kemPriv!!,
44 keys.dsaPriv!!
45 )
46 }
47
48 private data class PqcKeys(
49 val kemPub: ByteArray?,
50 val kemPriv: ByteArray?,
51 val dsaPub: ByteArray?,
52 val dsaPriv: ByteArray?
53 ) {
54 val isComplete: Boolean
55 get() = kemPub != null && kemPriv != null && hasDsaPair
56
57 private val hasDsaPair: Boolean
58 get() = dsaPub != null && dsaPriv != null
59 }
60
61 private suspend fun generateAndStore(store: E2eeKeyStore, prefix: String) {
62 val (kemPubNew, kemPrivNew) = Pqc.generateKem()
63 val (dsaPubNew, dsaPrivNew) = Pqc.generateDsa()
64 store.setBytes("${prefix}KemPub", kemPubNew, onlyIfAbsent = true)
65 store.setBytes("${prefix}KemPriv", kemPrivNew, onlyIfAbsent = true)
66 store.setBytes("${prefix}DsaPub", dsaPubNew, onlyIfAbsent = true)
67 store.setBytes("${prefix}DsaPriv", dsaPrivNew, onlyIfAbsent = true)
68 }
69 }
70}