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

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

Pqc.kt125 lines · 5.8 KiBRaw
1package com.vayunmathur.e2ee
2
3/**
4 * Post-quantum crypto primitives for the Office app, backed by native Rust
5 * (fips203 **ML-KEM-768** + fips204 **ML-DSA-65**) instead of Bouncy Castle:
6 * - ML-KEM-768 for encryption (key encapsulation + AES-256-GCM = hybrid PKE), and
7 * - ML-DSA-65 for signatures (authenticating edits and owner roster changes).
8 *
9 * Keys are handled as **DER** (X.509 SubjectPublicKeyInfo / PKCS#8), byte-compatible
10 * with the previously-deployed Bouncy Castle encoding — including BC's SHA-256
11 * single-step KDF over the ML-KEM shared secret — so existing identities and
12 * ciphertexts keep working. A device's public identity is a [bundle] of its
13 * ML-KEM and ML-DSA public keys.
14 *
15 * FindFamily additionally uses [generateLinkKey] for share links: ML-KEM only,
16 * derived from a 32-byte seed small enough to fit in a URL fragment.
17 */
18object Pqc {
19 /** Generate an ML-KEM keypair. Returns (kemPubDer, kemPrivDer). */
20 fun generateKem(): Pair<ByteArray, ByteArray> {
21 val kp = PqcNative.nativeMlkemKeygen() ?: error("ML-KEM keygen failed")
22 return kp[0] to kp[1]
23 }
24
25 /**
26 * A FindFamily share-link key. [seed] is the only secret — the ML-KEM keypair is
27 * derived from it, so the seed alone is what travels in the link and what needs
28 * storing. [publicBundle] has an empty ML-DSA half; nothing signs link data.
29 */
30 class LinkKey(val seed: ByteArray, val publicBundle: ByteArray)
31
32 /** Generate a fresh share-link key. */
33 fun generateLinkKey(): LinkKey {
34 val kp = PqcNative.nativeMlkemLinkKeygen() ?: error("ML-KEM link keygen failed")
35 return LinkKey(kp[0], bundle(kp[1], ByteArray(0)))
36 }
37
38 /** Re-derive a share-link public bundle from a stored 32-byte seed. */
39 fun linkPublicFromSeed(seed: ByteArray): ByteArray {
40 val kemPub = PqcNative.nativeMlkemLinkPubFromSeed(seed) ?: error("ML-KEM link derive failed")
41 return bundle(kemPub, ByteArray(0))
42 }
43
44 /** Generate an ML-DSA keypair. Returns (dsaPubDer, dsaPrivDer). */
45 fun generateDsa(): Pair<ByteArray, ByteArray> {
46 val kp = PqcNative.nativeMldsaKeygen() ?: error("ML-DSA keygen failed")
47 return kp[0] to kp[1]
48 }
49
50 // --- Public-key bundle = [4B kemLen][kemPub][dsaPub] ---
51
52 fun bundle(kemPub: ByteArray, dsaPub: ByteArray): ByteArray = lenPrefix(kemPub, dsaPub)
53
54 private fun splitBundle(b: ByteArray): Pair<ByteArray, ByteArray> = unLenPrefix(b)
55
56 /** Encrypts to a recipient bundle: ML-KEM encapsulate → AES-256-GCM. Layout `[4B encapLen][encap][aes]`. */
57 fun encryptTo(recipientBundle: ByteArray, plaintext: ByteArray): ByteArray {
58 val (kemPub, _) = splitBundle(recipientBundle)
59 val enc = PqcNative.nativeMlkemEncaps(kemPub) ?: error("ML-KEM encaps failed")
60 val encapsulation = enc[0]
61 val sharedSecret = enc[1]
62 val ct = E2ee.aesEncrypt(sharedSecret, plaintext)
63 return lenPrefix(encapsulation, ct)
64 }
65
66 /** Decrypts data from [encryptTo] with this identity's ML-KEM private key (DER). */
67 fun decrypt(kemPrivateDer: ByteArray, data: ByteArray): ByteArray {
68 val (encap, ct) = unLenPrefix(data)
69 val sharedSecret = PqcNative.nativeMlkemDecaps(kemPrivateDer, encap) ?: error("ML-KEM decaps failed")
70 return E2ee.aesDecrypt(sharedSecret, ct)
71 }
72
73 fun signWith(dsaPrivateDer: ByteArray, data: ByteArray): ByteArray =
74 PqcNative.nativeMldsaSign(dsaPrivateDer, data) ?: error("ML-DSA sign failed")
75
76 fun verify(bundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean = runCatching {
77 val (_, dsaPub) = splitBundle(bundle)
78 PqcNative.nativeMldsaVerify(dsaPub, data, signature)
79 }.getOrDefault(false)
80
81 /** Verification security code from two public bundles (identical on both devices when unmodified). */
82 fun securityCode(myBundle: ByteArray, peerBundle: ByteArray): String =
83 SecurityCode.compute(myBundle, peerBundle)
84
85 /** Short fingerprint of a bundle for invite links (see [InviteFingerprint]). */
86 fun inviteFingerprint(userId: Long, publicBundle: ByteArray): ByteArray =
87 InviteFingerprint.compute(userId, publicBundle)
88
89 // --- helpers ---
90
91 private fun lenPrefix(a: ByteArray, b: ByteArray): ByteArray {
92 val out = ByteArray(LEN_PREFIX_BYTES + a.size + b.size)
93 out[0] = (a.size ushr BYTE_THIRD_SHIFT).toByte()
94 out[1] = (a.size ushr BYTE_SECOND_SHIFT).toByte()
95 out[BYTE_SECOND_INDEX] = (a.size ushr BYTE_BITS).toByte()
96 out[BYTE_THIRD_INDEX] = a.size.toByte()
97 a.copyInto(out, LEN_PREFIX_BYTES)
98 b.copyInto(out, LEN_PREFIX_BYTES + a.size)
99 return out
100 }
101
102 private const val LEN_PREFIX_BYTES = 4
103 private const val BYTE_BITS = 8
104 private const val BYTE_SECOND_SHIFT = 16
105 private const val BYTE_THIRD_SHIFT = 24
106 private const val BYTE_SECOND_INDEX = 2
107 private const val BYTE_THIRD_INDEX = 3
108
109 private fun unLenPrefix(x: ByteArray): Pair<ByteArray, ByteArray> {
110 // Bundles/ciphertexts arrive from peers and storage; a truncated or
111 // lying length prefix must fail as IllegalArgumentException (the
112 // failure type callers already handle for bad crypto input), not as
113 // an IndexOutOfBoundsException from a raw array read.
114 require(x.size >= LEN_PREFIX_BYTES) { "length-prefixed data too short: ${x.size}" }
115 val len = ((x[0].toInt() and BYTE_MASK) shl BYTE_THIRD_SHIFT) or
116 ((x[1].toInt() and BYTE_MASK) shl BYTE_SECOND_SHIFT) or
117 ((x[BYTE_SECOND_INDEX].toInt() and BYTE_MASK) shl BYTE_BITS) or
118 (x[BYTE_THIRD_INDEX].toInt() and BYTE_MASK)
119 require(len >= 0 && LEN_PREFIX_BYTES + len <= x.size) { "length prefix $len exceeds size ${x.size}" }
120 return x.copyOfRange(LEN_PREFIX_BYTES, LEN_PREFIX_BYTES + len) to
121 x.copyOfRange(LEN_PREFIX_BYTES + len, x.size)
122 }
123
124 private const val BYTE_MASK = 0xFF
125}