Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / e2ee-p2p / src / test / java / com / vayunmathur / e2ee / E2eeHkdfIdentityTest.kt
E2eeHkdfIdentityTest.kt205 lines · 10.0 KiBRaw
| 1 | package com.vayunmathur.e2ee |
| 2 | |
| 3 | import javax.crypto.AEADBadTagException |
| 4 | import kotlin.test.Test |
| 5 | import kotlin.test.assertContentEquals |
| 6 | import kotlin.test.assertEquals |
| 7 | import kotlin.test.assertFailsWith |
| 8 | import kotlin.test.assertFalse |
| 9 | import kotlin.test.assertNotEquals |
| 10 | import kotlin.test.assertTrue |
| 11 | import kotlinx.coroutines.runBlocking |
| 12 | |
| 13 | /** HKDF vectors, AES-GCM round-trips, security codes, identity store lifecycle. */ |
| 14 | class E2eeHkdfIdentityTest { |
| 15 | |
| 16 | private fun hex(s: String): ByteArray = |
| 17 | ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } |
| 18 | |
| 19 | private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it.toInt() and 0xFF) } |
| 20 | |
| 21 | // RFC 5869 Test Case 1 (SHA-256). |
| 22 | @Test |
| 23 | fun hkdfRfc5869TestCase1() { |
| 24 | val ikm = ByteArray(22) { 0x0b } |
| 25 | val salt = hex("000102030405060708090a0b0c") |
| 26 | val info = hex("f0f1f2f3f4f5f6f7f8f9") |
| 27 | val okm = Hkdf.derive(ikm, info, 42, salt) |
| 28 | assertEquals( |
| 29 | "3cb25f25faacd57a90434f64d0362f2a" + |
| 30 | "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" + |
| 31 | "34007208d5b887185865", |
| 32 | okm.toHex(), |
| 33 | ) |
| 34 | } |
| 35 | |
| 36 | @Test |
| 37 | fun hkdfLengthsInfoSeparationAndLimit() { |
| 38 | val ikm = "secret".encodeToByteArray() |
| 39 | assertEquals(32, Hkdf.derive(ikm, "a".encodeToByteArray(), 32).size) |
| 40 | assertEquals(16, Hkdf.derive(ikm, "a".encodeToByteArray(), 16).size) |
| 41 | assertEquals(100, Hkdf.derive(ikm, "a".encodeToByteArray(), 100).size) |
| 42 | // Different info strings derive independent keys (domain separation). |
| 43 | val a = Hkdf.derive(ikm, "control".encodeToByteArray(), 32) |
| 44 | val b = Hkdf.derive(ikm, "media".encodeToByteArray(), 32) |
| 45 | assertFalse(a.contentEquals(b)) |
| 46 | // Prefix property: shorter derivations are prefixes of longer ones. |
| 47 | val full = Hkdf.derive(ikm, "x".encodeToByteArray(), 64) |
| 48 | assertContentEquals(full.copyOf(32), Hkdf.derive(ikm, "x".encodeToByteArray(), 32)) |
| 49 | // Default (zero) salt still works; explicit salt changes the output. |
| 50 | assertFalse( |
| 51 | Hkdf.derive(ikm, "x".encodeToByteArray(), 32) |
| 52 | .contentEquals(Hkdf.derive(ikm, "x".encodeToByteArray(), 32, ByteArray(32) { 1 })), |
| 53 | ) |
| 54 | assertFailsWith<IllegalArgumentException> { |
| 55 | Hkdf.derive(ikm, "x".encodeToByteArray(), 255 * 32 + 1) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | @Test |
| 60 | fun aesRoundTripTamperAndWrongKey() { |
| 61 | val key = E2ee.newContentKey() |
| 62 | assertEquals(32, key.size) |
| 63 | assertFalse(E2ee.newContentKey().contentEquals(E2ee.newContentKey())) |
| 64 | val plain = "vault contents — ütf8 ✓".encodeToByteArray() |
| 65 | val ct = E2ee.aesEncrypt(key, plain) |
| 66 | // IV (12) prepended + GCM tag (16) appended by the cipher. |
| 67 | assertEquals(plain.size + 12 + 16, ct.size) |
| 68 | assertContentEquals(plain, E2ee.aesDecrypt(key, ct)) |
| 69 | assertContentEquals(ByteArray(0), E2ee.aesDecrypt(key, E2ee.aesEncrypt(key, ByteArray(0)))) |
| 70 | // Tampered ciphertext fails authentication rather than decrypting. |
| 71 | val tampered = ct.copyOf().also { it[it.size - 1] = (it[it.size - 1] + 1).toByte() } |
| 72 | assertFailsWith<AEADBadTagException> { E2ee.aesDecrypt(key, tampered) } |
| 73 | assertFailsWith<Exception> { E2ee.aesDecrypt(E2ee.newContentKey(), ct) } |
| 74 | // Random IV: same plaintext encrypts differently each time. |
| 75 | assertFalse(ct.contentEquals(E2ee.aesEncrypt(key, plain))) |
| 76 | } |
| 77 | |
| 78 | @Test |
| 79 | fun securityCodeSymmetricFormattedAndKeySensitive() { |
| 80 | val a = byteArrayOf(1, 2, 3, 4) |
| 81 | val b = byteArrayOf(5, 6, 7, 8) |
| 82 | val code = SecurityCode.compute(a, b) |
| 83 | assertEquals(code, SecurityCode.compute(b, a)) |
| 84 | // Six groups of five digits. |
| 85 | assertTrue(code.matches(Regex("""\d{5}( \d{5}){5}""")), "unexpected format: $code") |
| 86 | assertNotEquals(code, SecurityCode.compute(a, byteArrayOf(9, 9, 9))) |
| 87 | assertEquals(code, SecurityCode.compute(a.copyOf(), b.copyOf())) |
| 88 | } |
| 89 | |
| 90 | private class MemStore : E2eeKeyStore { |
| 91 | val map = mutableMapOf<String, ByteArray>() |
| 92 | var writes = 0 |
| 93 | override suspend fun getBytes(name: String): ByteArray? = map[name] |
| 94 | override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) { |
| 95 | if (onlyIfAbsent && map.containsKey(name)) return |
| 96 | map[name] = value |
| 97 | writes++ |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | @Test |
| 102 | fun identityLoadOrCreatePersistsAndReloads() = runBlocking { |
| 103 | // Native like PqcTest: the host lib is built for JVM tests, so an |
| 104 | // unavailable lib is a build failure, not a silent pass. |
| 105 | val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess |
| 106 | assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests") |
| 107 | val store = MemStore() |
| 108 | val first = PqcIdentity.loadOrCreate(store) |
| 109 | assertTrue(store.map.keys.containsAll(setOf("pqcKemPub", "pqcKemPriv", "pqcDsaPub", "pqcDsaPriv"))) |
| 110 | assertTrue(first.publicBundle.isNotEmpty()) |
| 111 | // Second load reuses the persisted identity, byte for byte. |
| 112 | val second = PqcIdentity.loadOrCreate(store) |
| 113 | assertContentEquals(first.publicBundle, second.publicBundle) |
| 114 | // Custom prefix keeps stores apart. |
| 115 | val other = PqcIdentity.loadOrCreate(store, prefix = "alt") |
| 116 | assertFalse(first.publicBundle.contentEquals(other.publicBundle)) |
| 117 | assertTrue(store.map.containsKey("altKemPub")) |
| 118 | // Encrypt-to-self / sign-verify through the loaded identity. |
| 119 | val ct = Pqc.encryptTo(first.publicBundle, "hello".encodeToByteArray()) |
| 120 | assertContentEquals("hello".encodeToByteArray(), first.decrypt(ct)) |
| 121 | val sig = first.sign("data".encodeToByteArray()) |
| 122 | assertTrue(Pqc.verify(first.publicBundle, "data".encodeToByteArray(), sig)) |
| 123 | } |
| 124 | |
| 125 | @Test |
| 126 | fun identityIncompleteStoreRegenerates() = runBlocking { |
| 127 | val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess |
| 128 | assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests") |
| 129 | val store = MemStore() |
| 130 | // Only half an identity persisted: treated as absent, not as a broken identity. |
| 131 | store.map["pqcKemPub"] = byteArrayOf(1, 2, 3) |
| 132 | store.map["pqcKemPriv"] = byteArrayOf(4, 5, 6) |
| 133 | val identity = PqcIdentity.loadOrCreate(store) |
| 134 | // The onlyIfAbsent winner for KemPub is the stale value, so the re-read bundle |
| 135 | // is built from persisted (stale-Kem + fresh-DSA) parts; what matters is that |
| 136 | // loadOrCreate completes and persists a full set rather than erroring. |
| 137 | assertTrue(store.map.containsKey("pqcDsaPub")) |
| 138 | assertTrue(identity.publicBundle.isNotEmpty()) |
| 139 | } |
| 140 | |
| 141 | private fun assertIdentityUsable(identity: PqcIdentity) { |
| 142 | val payload = "pair-check payload".encodeToByteArray() |
| 143 | val ciphertext = Pqc.encryptTo(identity.publicBundle, payload) |
| 144 | assertContentEquals(payload, identity.decrypt(ciphertext)) |
| 145 | val signed = "pair-check signed".encodeToByteArray() |
| 146 | assertTrue(Pqc.verify(identity.publicBundle, signed, identity.sign(signed))) |
| 147 | } |
| 148 | |
| 149 | @Test |
| 150 | fun identityIncompleteStoreHealsToUsableIdentity() = runBlocking { |
| 151 | val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess |
| 152 | assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests") |
| 153 | val store = MemStore() |
| 154 | // Regression: previously the stale 3-byte halves won the onlyIfAbsent stores, so |
| 155 | // the re-read identity was complete on paper but its KEM half could not even be |
| 156 | // encapsulated to, and that state then persisted for every later load. |
| 157 | store.map["pqcKemPub"] = byteArrayOf(1, 2, 3) |
| 158 | store.map["pqcKemPriv"] = byteArrayOf(4, 5, 6) |
| 159 | val identity = PqcIdentity.loadOrCreate(store) |
| 160 | assertIdentityUsable(identity) |
| 161 | // The healed identity is the one persisted: a reload yields it byte for byte. |
| 162 | val reloaded = PqcIdentity.loadOrCreate(store) |
| 163 | assertContentEquals(identity.publicBundle, reloaded.publicBundle) |
| 164 | assertIdentityUsable(reloaded) |
| 165 | } |
| 166 | |
| 167 | @Test |
| 168 | fun identityLoneValidKemPubIsNotPairedWithFreshPrivate() = runBlocking { |
| 169 | val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess |
| 170 | assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests") |
| 171 | val store = MemStore() |
| 172 | // Regression: a crash after the first store kept this valid KEM public half; the |
| 173 | // old code paired it with a different generation's private half, so ciphertexts |
| 174 | // to the advertised bundle failed AES-GCM on decrypt. |
| 175 | val (kemPub, _) = Pqc.generateKem() |
| 176 | store.map["pqcKemPub"] = kemPub |
| 177 | val identity = PqcIdentity.loadOrCreate(store) |
| 178 | assertIdentityUsable(identity) |
| 179 | val reloaded = PqcIdentity.loadOrCreate(store) |
| 180 | assertContentEquals(identity.publicBundle, reloaded.publicBundle) |
| 181 | } |
| 182 | |
| 183 | @Test |
| 184 | fun identityMismatchedCompletePairsAreReplaced() = runBlocking { |
| 185 | val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess |
| 186 | assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests") |
| 187 | val store = MemStore() |
| 188 | // Regression: two interleaved first-time stores (or a torn write) can leave a |
| 189 | // complete set whose public and private halves come from different generations. |
| 190 | // Presence of all four entries must not be taken as a usable identity. |
| 191 | val (kemPubA, _) = Pqc.generateKem() |
| 192 | val (_, kemPrivB) = Pqc.generateKem() |
| 193 | val (dsaPubA, _) = Pqc.generateDsa() |
| 194 | val (_, dsaPrivB) = Pqc.generateDsa() |
| 195 | store.map["pqcKemPub"] = kemPubA |
| 196 | store.map["pqcKemPriv"] = kemPrivB |
| 197 | store.map["pqcDsaPub"] = dsaPubA |
| 198 | store.map["pqcDsaPriv"] = dsaPrivB |
| 199 | val identity = PqcIdentity.loadOrCreate(store) |
| 200 | assertIdentityUsable(identity) |
| 201 | val reloaded = PqcIdentity.loadOrCreate(store) |
| 202 | assertContentEquals(identity.publicBundle, reloaded.publicBundle) |
| 203 | assertIdentityUsable(reloaded) |
| 204 | } |
| 205 | } |