From c2bba7bcf713fabc3124633d67c59f3509e33a22 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Fri, 9 Jan 2026 21:06:46 +0100 Subject: [PATCH 01/19] update: added new method for agreeing with nonce --- .../CryptoHelpers.java | 4 +- .../SecurityCurve25519.kt | 37 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java index df6ed86..cdea976 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java @@ -85,9 +85,7 @@ public static Mac HMAC256(byte[] data) throws GeneralSecurityException { public static byte[] generateRandomBytes(int length) { SecureRandom random = new SecureRandom(); - byte[] bytes = new - - byte[length]; + byte[] bytes = new byte[length]; random.nextBytes(bytes); return bytes; } diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt index 9382dbb..dd62d59 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt @@ -7,6 +7,43 @@ class SecurityCurve25519(val privateKey: ByteArray = Curve25519.generateRandomKe return Curve25519.publicKey(this.privateKey) } + fun agreeWithAuthAndNonce( + authenticationPublicKey: ByteArray, + publicKey: ByteArray, + salt: ByteArray, + nonce1: ByteArray, + nonce2: ByteArray, + info: ByteArray, + ): ByteArray { + val handshakeSalt = nonce1 + nonce2 + val dh1 = Curve25519.sharedSecret(this.privateKey, authenticationPublicKey) + val dh2 = Curve25519.sharedSecret(this.privateKey, publicKey) + var ck = CryptoHelpers.HKDF( + "HMACSHA256", + handshakeSalt, + salt, + info, + 32, + 1 + )[0] + ck = CryptoHelpers.HKDF( + "HMACSHA256", + dh1, + ck, + info, + 32, + 1 + )[0] + return CryptoHelpers.HKDF( + "HMACSHA256", + dh2, + ck, + info, + 32, + 1 + )[0] + } + fun calculateSharedSecret(publicKey: ByteArray): ByteArray { val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) return CryptoHelpers.HKDF("HMACSHA256", sharedKey, null, From 433c1fde62f7ab3654106dc3c1ef6d6367b012b1 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Sun, 11 Jan 2026 18:48:12 +0100 Subject: [PATCH 02/19] update: removed python files --- .../CryptoHelpers.java | 4 +- .../SecurityCurve25519.kt | 37 ------------------- 2 files changed, 3 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java index cdea976..df6ed86 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java @@ -85,7 +85,9 @@ public static Mac HMAC256(byte[] data) throws GeneralSecurityException { public static byte[] generateRandomBytes(int length) { SecureRandom random = new SecureRandom(); - byte[] bytes = new byte[length]; + byte[] bytes = new + + byte[length]; random.nextBytes(bytes); return bytes; } diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt index dd62d59..9382dbb 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt @@ -7,43 +7,6 @@ class SecurityCurve25519(val privateKey: ByteArray = Curve25519.generateRandomKe return Curve25519.publicKey(this.privateKey) } - fun agreeWithAuthAndNonce( - authenticationPublicKey: ByteArray, - publicKey: ByteArray, - salt: ByteArray, - nonce1: ByteArray, - nonce2: ByteArray, - info: ByteArray, - ): ByteArray { - val handshakeSalt = nonce1 + nonce2 - val dh1 = Curve25519.sharedSecret(this.privateKey, authenticationPublicKey) - val dh2 = Curve25519.sharedSecret(this.privateKey, publicKey) - var ck = CryptoHelpers.HKDF( - "HMACSHA256", - handshakeSalt, - salt, - info, - 32, - 1 - )[0] - ck = CryptoHelpers.HKDF( - "HMACSHA256", - dh1, - ck, - info, - 32, - 1 - )[0] - return CryptoHelpers.HKDF( - "HMACSHA256", - dh2, - ck, - info, - 32, - 1 - )[0] - } - fun calculateSharedSecret(publicKey: ByteArray): ByteArray { val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) return CryptoHelpers.HKDF("HMACSHA256", sharedKey, null, From 1d4745f02cff089ee1ec87b4a95f849c692e5ce9 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Mon, 12 Jan 2026 11:55:30 +0100 Subject: [PATCH 03/19] update: brought back the files --- src/androidTest/java/com/afkanerd/.DS_Store | Bin 0 -> 8196 bytes .../com/afkanerd/smswithoutborders/.DS_Store | Bin 0 -> 6148 bytes .../SecurityRSATest.java | 14 +- .../SecurityX25519Test.kt | 40 +++- .../libsignal/RatchetsTest.kt | 105 ++++++++- .../libsignal/StateTest.kt | 10 +- src/main/java/com/afkanerd/.DS_Store | Bin 0 -> 8196 bytes .../com/afkanerd/smswithoutborders/.DS_Store | Bin 0 -> 6148 bytes .../libsignal_doubleratchet/.DS_Store | Bin 0 -> 8196 bytes .../CryptoHelpers.java | 8 +- .../EncryptionController.kt | 8 +- .../SecurityCurve25519.kt | 105 ++++++++- .../extensions/context.kt | 9 +- .../libsignal/Protocols.java | 79 ++++++- .../libsignal/RatchetsHE.kt | 213 ++++++++++++++++++ .../libsignal/States.java | 165 -------------- .../libsignal/States.kt | 61 +++++ 17 files changed, 613 insertions(+), 204 deletions(-) create mode 100644 src/androidTest/java/com/afkanerd/.DS_Store create mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/.DS_Store create mode 100644 src/main/java/com/afkanerd/.DS_Store create mode 100644 src/main/java/com/afkanerd/smswithoutborders/.DS_Store create mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/.DS_Store create mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.java create mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt diff --git a/src/androidTest/java/com/afkanerd/.DS_Store b/src/androidTest/java/com/afkanerd/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..e4cabc01e52098fdca113b7b1e2b256e9e9e627e GIT binary patch literal 8196 zcmeHMU2GIp6u#fI&{;arDYQ~*2R2=ZfNfb?pye;w{we=Owx!!rSax?tIxss^c4l|M zQq!3DBB1d}<6rd2A0iJbYIxB^QS?#K1Y?ZBX#9E5L|;@MJTrF|Y=MLa0~+Th_nv$1 zx#!+{&YbVwo-JbxU3qmSV|9!%k*Z7ON@}iCT)A7XDS|&zP86iin9dwF$}E;A8kE2T zfd>K)1Re-H5P0C<=mC1O-6G!L-RIJv4LlHd;D6}>_kIXdb!p6}lbm{22Q^*_K-5hE zyh44-13aCuPh&ov`Ulo3e0j^H+usfY-%%_u_a&-o-&fxD1KSP1HJL!eJ z=?pPWgEsI$;DKvB;KHYx*(^)7I3<5iQy!mVD$}U7(?xqMZCGiVeKtL2=(ZD$eh#6m ze8$WQu|ljA_r^!9V%$kNdAlo>+v9TmmSv<%{Zx9lt`(DVO}Aw_Dc#g^o`SAwG-YH^ zH&v_HW#vuP_H^T1Acn+HQm!8#Z(iBDrYXF#ZB2BdDLlTmHQE$j)wX70A|%#ER;=HZ zJY-}|>jXCs{uRMyPc!%A&Dm<$g>G(ZS-fQH7bROmvnr+8%3xw>SQ<&na|>it-4T{1iTvaGdP2|)1;k@n~l_R3)?GaWQr4f}5x7||RT~tv%L+jA)OO!@s zk1OfUY1FE|!ZPJoNVfS%o3vUPFj8sF2+1nnr$bt&3>LWm zL-JNWxKXNA5*aI-B@^usAL~@Qm3{8E+fugEH>R2Hk zdY_cWU8P=CcPvjx-q_KoC`0aYovP~DP+zy8N{K52qWp1H-_(V8LotwCD2!#HHBb>fI2pjI*w0VoP?LPy;i*r2K)zscG zKfGl5id7vOJFkQ%kLOYd{~Z_}8m3^#LxUGB(<1qThfitYq7oplLX<;xfMBE@5nVLP z75?nVVv%4Z&+yr$%ZS}7&*W@FbBjojl?9KL8d}>z1WdWiXPeuJ1!tu78$tw8x!h+L z#)xGe)6me#eXXPFS1MQd-e;vOz}Sl^H7Jo5T&T^!Y1tS;y#W6>_Za!k%o#a zOjtNf2snlbJcvm=MDc%u5bzit$5VJ3&kzb;#7lS?r|>Fa;4Qq3vv?2h;~YNp(eNc< z;Ya*5Exxx;jc@#RbMak>=S;&g576uqQl>6+3%D}AN1dDh_ulyT|66d9V2i*5fd_7v z2TQ(c{yPbWF05h}O* Whk)DlM|kl52k-yYg!;C>|9=7YAf>7R literal 0 HcmV?d00001 diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/.DS_Store b/src/androidTest/java/com/afkanerd/smswithoutborders/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..68565d064e7e8f286bb29c4a9f83e012e5578add GIT binary patch literal 6148 zcmeHKyKVw85S&dYkkZgW>0ihnSO~r#9}ohE5~Nd33eaDd-_Gmm`Uq1H>BGJ2FBOrxKki(PD_x884An1A9lOL!$YRxLKk@ z5xbq|7fXj!#~f3ERA8vUqc3M#|JU>@{r`}Zt5hHrxGM!@vU*u9`J||=qsM8jE%Xij qV$8L44pxeZR*JdMQoQ(;S9H$(8rVA;opGZR^G85+NlOL(LxCSaks2KU literal 0 HcmV?d00001 diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java index ec9ebd2..98487f6 100644 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java +++ b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java @@ -43,12 +43,12 @@ public void testCanStoreAndEncrypt() throws NoSuchAlgorithmException, NoSuchProv // .build()); // // KeyPair keyPair = kpg.generateKeyPair(); - PublicKey publicKey = SecurityRSA.generateKeyPair(keystoreAlias, 2048); - KeyPair keyPair = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias); - - SecretKey secretKey = SecurityAES.generateSecretKey(256); - byte[] cipherText = SecurityRSA.encrypt(keyPair.getPublic(), secretKey.getEncoded()); - byte[] plainText = SecurityRSA.decrypt(keyPair.getPrivate(), cipherText); - assertArrayEquals(secretKey.getEncoded(), plainText); +// PublicKey publicKey = SecurityRSA.generateKeyPair(keystoreAlias, 2048); +// KeyPair keyPair = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias); +// +// SecretKey secretKey = SecurityAES.generateSecretKey(256); +// byte[] cipherText = SecurityRSA.encrypt(keyPair.getPublic(), secretKey.getEncoded()); +// byte[] plainText = SecurityRSA.decrypt(keyPair.getPrivate(), cipherText); +// assertArrayEquals(secretKey.getEncoded(), plainText); } } diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt index 52a1f89..b8fa7c2 100644 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt +++ b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt @@ -1,12 +1,50 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties import androidx.test.filters.SmallTest -import junit.framework.TestCase.assertEquals import org.junit.Assert.assertArrayEquals import org.junit.Test +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.Signature @SmallTest class SecurityX25519Test { + @Test + fun keystoreEd25519() { + val keystoreAlias = "keystoreAlias" + val kpg: KeyPairGenerator = KeyPairGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_EC, + "AndroidKeyStore" + ) + val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder( + keystoreAlias, + KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY + ).run { + setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) + build() + } + + kpg.initialize(parameterSpec) + val kp = kpg.generateKeyPair() + + val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { + load(null) + } + val entry: KeyStore.Entry = ks.getEntry(keystoreAlias, null) + if (entry !is KeyStore.PrivateKeyEntry) { + throw Exception("No instance of keystore") + } + + val data = "Hello world".encodeToByteArray() + val signature: ByteArray = Signature.getInstance("SHA256withECDSA").run { + initSign(entry.privateKey) + update(data) + sign() + } + + } @Test fun sharedSecret() { diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index 63a8fc3..63c31af 100644 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -5,6 +5,7 @@ import androidx.core.util.component1 import androidx.core.util.component2 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityCurve25519 import org.junit.Assert.assertArrayEquals import org.junit.Test @@ -14,6 +15,108 @@ import java.security.SecureRandom class RatchetsTest { var context: Context = InstrumentationRegistry.getInstrumentation().targetContext + @Test + fun completeRatchetHETest() { + val aliceEphemeralKeyPair = SecurityCurve25519() + val aliceEphemeralHeaderKeyPair = SecurityCurve25519() + val aliceEphemeralNextHeaderKeyPair = SecurityCurve25519() + + val bobStaticKeyPair = SecurityCurve25519() + val bobEphemeralKeyPair = SecurityCurve25519() + val bobEphemeralHeaderKeyPair = SecurityCurve25519() + val bobEphemeralNextHeaderKeyPair = SecurityCurve25519() + + val aliceNonce = CryptoHelpers.generateRandomBytes(16) + val bobNonce = CryptoHelpers.generateRandomBytes(16) + + val (aliceSk, aliceSkH, aliceSkNh) = SecurityCurve25519(aliceEphemeralKeyPair.privateKey) + .agreeWithAuthAndNonce( + authenticationPublicKey = bobStaticKeyPair.generateKey(), + authenticationPrivateKey = null, + headerPrivateKey = aliceEphemeralHeaderKeyPair.privateKey, + nextHeaderPrivateKey = aliceEphemeralNextHeaderKeyPair.privateKey, + publicKey = bobEphemeralKeyPair.generateKey(), + headerPublicKey = bobEphemeralHeaderKeyPair.generateKey(), + nextHeaderPublicKey = bobEphemeralNextHeaderKeyPair.generateKey(), + salt = "RelaySMS v1".encodeToByteArray(), + nonce1 = aliceNonce, + nonce2 = bobNonce, + info = "RelaySMS C2S DR v1".encodeToByteArray() + ) + + val (bobSk, bobSkH, bobSkNh) = SecurityCurve25519(bobEphemeralKeyPair.privateKey) + .agreeWithAuthAndNonce( + authenticationPublicKey = null, + authenticationPrivateKey = bobStaticKeyPair.privateKey, + headerPrivateKey = bobEphemeralHeaderKeyPair.privateKey, + nextHeaderPrivateKey = bobEphemeralNextHeaderKeyPair.privateKey, + publicKey = aliceEphemeralKeyPair.generateKey(), + headerPublicKey = aliceEphemeralHeaderKeyPair.generateKey(), + nextHeaderPublicKey = aliceEphemeralNextHeaderKeyPair.generateKey(), + salt = "RelaySMS v1".encodeToByteArray(), + nonce1 = aliceNonce, + nonce2 = bobNonce, + info = "RelaySMS C2S DR v1".encodeToByteArray() + ) + + assertArrayEquals(aliceSk, bobSk) + assertArrayEquals(aliceSkH, bobSkH) + assertArrayEquals(aliceSkNh, bobSkNh) + + val aliceState = States() + RatchetsHE.ratchetInitAlice( + state = aliceState, + SK = aliceSk, + bobDhPublicKey = bobEphemeralKeyPair.generateKey(), + sharedHka = aliceSkH, + sharedNhkb = aliceSkNh + ) + + val bobState = States() + RatchetsHE.ratchetInitBob( + state = bobState, + SK = bobSk, + bobDhPublicKeypair = bobEphemeralKeyPair.getKeypair(), + sharedHka = bobSkH, + sharedNhkb = bobSkNh + ) + + val originalText = SecureRandom.getSeed(32); + val (encHeader, aliceCipherText) = RatchetsHE.ratchetEncrypt( + aliceState, + originalText, + bobStaticKeyPair.generateKey() + ) + + var encHeader1: ByteArray? = null + var aliceCipherText1: ByteArray? = null + for(i in 1..10) { + val (encHeader2, aliceCipherText2) = RatchetsHE.ratchetEncrypt( + aliceState, + originalText, + bobStaticKeyPair.generateKey() + ) + encHeader1 = encHeader2 + aliceCipherText1 = aliceCipherText2 + } + + val bobPlainText = RatchetsHE.ratchetDecrypt( + state = bobState, + encHeader = encHeader, + cipherText = aliceCipherText, + AD = bobStaticKeyPair.generateKey() + ) + + val bobPlainText1 = RatchetsHE.ratchetDecrypt( + state = bobState, + encHeader = encHeader1!!, + cipherText = aliceCipherText1!!, + AD = bobStaticKeyPair.generateKey() + ) + + assertArrayEquals(originalText, bobPlainText) + assertArrayEquals(originalText, bobPlainText1) + } @Test fun completeRatchetTest() { @@ -48,7 +151,7 @@ class RatchetsTest { val bobPlainText1 = Ratchets.ratchetDecrypt(bobState, header1, aliceCipherText1, bob.generateKey()) - println(bobState.serializedStates) + println(bobState.serialize()) assertArrayEquals(originalText, bobPlainText) assertArrayEquals(originalText, bobPlainText1) diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt index 42e3d84..42c254e 100644 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt +++ b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt @@ -2,6 +2,7 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal import androidx.test.filters.SmallTest import junit.framework.TestCase.assertEquals +import kotlinx.serialization.json.Json import org.junit.Test import java.security.SecureRandom @@ -12,11 +13,8 @@ class StateTest { val state = States() state.DHs = android.util.Pair(SecureRandom.getSeed(32), SecureRandom.getSeed(32)) - val serializedStates = state.serializedStates - println("Encoded values: $serializedStates") - val state1 = States(serializedStates) - println(state1.serializedStates) - - assertEquals(state, state1) + val serializedStates = Json.encodeToString(state) + val deserializedStates = Json.decodeFromString(serializedStates) + assertEquals(state, deserializedStates) } } \ No newline at end of file diff --git a/src/main/java/com/afkanerd/.DS_Store b/src/main/java/com/afkanerd/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..fce4432f14a4875ae269202cf8c22cbcca51223b GIT binary patch literal 8196 zcmeHMU2GIp6u#fI&>1?=DYQ~*M>buEfGxD;r{yo%{we=Owx!!rSax?tIxss^c4l|M zQq!3DqM-3f<6rd2A0iJbYIxB^QS?#K1Y?ZBX#9E5L|;@MJTrF|Y=MLa0~+Th_nv$1 zx#!+{&YbVwo-JbxU3smQu{y?>NY$fCB{kP5p4_Wf6(JZYCkoPM%wR4XWj4zb4NK^O z&;y|dLJx!<2tDv`^Z>otUJH09Pk@#G6hu7SKsfxjF+^X9#vikfFfeo%AC9 zbcPtGVH7p~1HtjUcK9e3Z4aaS1`5Z!7 z`HYzrVue^K?v0Py#kiYt^G;VPx5wl9ZQD$j`l2Q--DId<8?(Y0Ai; zVQF@;%g$SxR@7MSRP3#a|>it-it$Kt4q~r zlFnDvEvUb}K~?#LD+;BliG12PoHyK~N>mj6JtAtOJfhLzw%eMwizX_kX&u^qvD&Ea z@g&_jomwqWSgPJ7_d8^RsHFJB<#LPMe~7|EQXD?AQeLeNn5ndGN{Yt!>5$i{g9Yw? zN!iK=H_EkYB4cN>WTGSSu}-yH-REt)E#quX)VMkzDxZk-i43b?5G3fca%70n(x-{W zmho=%-2-3yJ?`jetc8!$bEvX5*2A{3{RF^qc7i?0PO>-HS@r?@jD5v^V86280n9`N zW}y-_sK+8SVKv&(fwkyDA9i9F;uygw3><`mBRGn29K%C+7?0ot9>o)Q7SG{%ynt8m z8eYd~yoq;k4jFCoTyyg!w|9us~=OnuKOyxzH|j2+Pp>H_MZXag*iU#YHDwr zA6dL?#j1{totMLt$8#x!{|*cv4O1}Wqrs1sX_0*1$ESS9!V(~_K$JsvfMBE_5j`|3 z6~XN2B9UOE%m~;eONrg8%;aoC^Ky|Os|Y?TH?*yk2$)J)z&5uN3(m;vH%J6gr95Eo zh!M+trlFyymzFuFi2qdlUtky6_v{yTiQ<0_=AjOEqJ^Tq3!AXRkNY?Vun$S>M;aQk zuwdgbA>bG$@Bk+9AjSW2Lcn8q98ckCJVPjW5ij9ooW!eyfw%BB&fq<~kF)qNK*N`W zg&*A@xn>Wd+uR@KVjuZ9MaiW+1VMzT5P4#qQ0iEQOMyTBM W9|CUGAK~HqAHM%r66#z2{{IDVccrob literal 0 HcmV?d00001 diff --git a/src/main/java/com/afkanerd/smswithoutborders/.DS_Store b/src/main/java/com/afkanerd/smswithoutborders/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..68565d064e7e8f286bb29c4a9f83e012e5578add GIT binary patch literal 6148 zcmeHKyKVw85S&dYkkZgW>0ihnSO~r#9}ohE5~Nd33eaDd-_Gmm`Uq1H>BGJ2FBOrxKki(PD_x884An1A9lOL!$YRxLKk@ z5xbq|7fXj!#~f3ERA8vUqc3M#|JU>@{r`}Zt5hHrxGM!@vU*u9`J||=qsM8jE%Xij qV$8L44pxeZR*JdMQoQ(;S9H$(8rVA;opGZR^G85+NlOL(LxCSaks2KU literal 0 HcmV?d00001 diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/.DS_Store b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d661d7f9ee81c45fc4021d238049ba5b09d10fbe GIT binary patch literal 8196 zcmeHMU2GIp6u#fIrL%OP1GLg&M>buEfGsTLr{yo%{we=Owx!!rSY~&|c3?VFc4oI= zscB4n5zzRg@h|%150M8I|6Vjv6n#`Q!5CvO8h;)%(HE5m&&-|Wr!8+{YMh(QJ@=e* z&%O7Y`Oe%uEn^IAd2KagHHqQ)Y*P zFalu&!U%*B2qO?iU?xO>?rg7#H@Ww@HtfR)gc0~(M!@?%MCtKpBA^qT`kxN!{1Sj@ zDT)0?W2ysun`l520iEE~H>EXs^?<+>L5TrwPWq@fooFJU6P$8$25!y}?2Mp7fxkQ1 zMg8dv2~NX4j6fKHsS)sM_Xsnoa?dd5`ug1&$(VMAv~OodOv7>G@h>2hl$OmZ7t6&8 z@j!CO9!tJ-bLRSiqe`38oj)0BZ;!_w^0Hal-= zj&Gaf3Na!^(sJ$CSmTD(4bj!>;_Js7qGKDH;tkQYYu1mCN5tybs!e;-N6cZ%KFPg7 z@I_#ACV6*ide<~3Yi8)Ep4l{>n@*vfdtQ<(dj4h6^T_N9X^zsH>g$&V((?QQx!5)0 z8n)%^({m2dv|Q;>D7Iy7Yfn!1^u1Zz%nw^mTAr6x&1~LOUA@&blg9lz$ts;}&Nj_G zwqtn9^rc+=nCt1Ls8aooopam$#nQ5zcl5nFtz{JS4qDMk8MLKmST!jMh@73faPg95 zjZMv)6P??3-FvZ8o;QDiR4w&W%q`cr&(L#ys*}|%&9DZ0Mh(p!>Ma@xYT`wz!H%iE?Fb3Q+iA_qni;~0P4)*5E|j zN$S5+l6yv-n&H~MlA^J@UQznIb^|Pp~uWb#|V8$UbLZvme=S><<95 zP>$KCKou5Y2^z2t&1k^}w4n=ouop=TU%TdKHcwzeUJip9ntsZ^#)R{XRM-A@`!6kJ25BiwSrwC3%YWP}=CnL@#^g z@?dssiAZT9mj&#y<;3ogXK}W!aivHpDhoa<)ite&P$J4D0o&M2EI1==+8m*jluHBl zjs&sHXX@%YI%$~;viMKo{Sv#(eqg_{D}?vCSb!Sbi8!IW4O_9>$9WPxIEXY3Ap;G= zuwdgTA^rr$@c<_9AmRNKA^uT3h9~h9o+i}4fEV!+&fpco{F`_S@8ErWfb;k$K>t^S z{h#pjBs}lB5zqL2dOR1BIm@)ILDCj8;YPz5!Ikh+)OhuO=gt5AKO@c>9wLlD7=c?8 z0hD$mJKAXNn|-UiT02V5A$q*#&70uVH=)ii$BFvoIMJ*BFr;ymrg}DsfKG5q5^DeY W9|ETQvc4rhy2JZFy#HtP{r@) { + val handshakeSalt = nonce1 + nonce2 + val headerInfo = "RelaySMS C2S DRHE v1".encodeToByteArray() + + val rootKey = agreeWithAuthAndNonceImpl( + authenticationPublicKey = authenticationPublicKey, + authenticationPrivateKey = authenticationPrivateKey, + publicKey = publicKey, + salt = salt, + info = info, + handshakeSalt = handshakeSalt, + ) + + val headerKey = agreeWithAuthAndNonceImpl( + authenticationPublicKey = authenticationPublicKey, + authenticationPrivateKey = authenticationPrivateKey, + publicKey = headerPublicKey, + salt = salt, + info = headerInfo, + handshakeSalt = handshakeSalt, + privateKey = headerPrivateKey + ) + + val nextHeaderKey = agreeWithAuthAndNonceImpl( + authenticationPublicKey = authenticationPublicKey, + authenticationPrivateKey = authenticationPrivateKey, + publicKey = nextHeaderPublicKey, + salt = salt, + info = headerInfo, + handshakeSalt = handshakeSalt, + privateKey = nextHeaderPrivateKey + ) + + return Triple(rootKey, headerKey, nextHeaderKey) + } + + fun calculateSharedSecret( + publicKey: ByteArray, + salt: ByteArray? = null, + info: ByteArray? = "x25591_key_exchange".encodeToByteArray(), + ): ByteArray { val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) - return CryptoHelpers.HKDF("HMACSHA256", sharedKey, null, - "x25591_key_exchange".encodeToByteArray(), 32, 1)[0] + return CryptoHelpers.HKDF( + "HMACSHA256", + sharedKey, + salt, + info, + 32, + 1 + )[0] } fun getKeypair(): android.util.Pair { diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt index 7b2c70c..fbc7020 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt @@ -11,20 +11,14 @@ import androidx.datastore.preferences.preferencesDataStore import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityRSA import com.google.gson.Gson -import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map import java.io.IOException -import java.security.KeyFactory import java.security.KeyPair import java.security.KeyStore import java.security.KeyStoreException import java.security.NoSuchAlgorithmException import java.security.UnrecoverableEntryException import java.security.cert.CertificateException -import java.security.spec.PKCS8EncodedKeySpec -import java.security.spec.X509EncodedKeySpec -import javax.crypto.SecretKey import javax.crypto.spec.SecretKeySpec val Context.dataStore: DataStore by preferencesDataStore(name = "secure_comms") @@ -134,8 +128,7 @@ suspend fun Context.saveBinaryDataEncrypted( @Throws suspend fun Context.getEncryptedBinaryData(keystoreAlias: String): ByteArray? { val keyValue = stringPreferencesKey(keystoreAlias) - val data = dataStore.data.first()[keyValue] - if(data == null) return null + val data = dataStore.data.first()[keyValue] ?: return null val savedBinaryData = Gson().fromJson(data, SavedBinaryData::class.java) diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java index 976ae94..3776adc 100644 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.security.GeneralSecurityException; +import java.util.ArrayList; import javax.crypto.Mac; @@ -29,14 +30,36 @@ */ public class Protocols { final static int HKDF_LEN = 32; - final static int HKDF_NUM_KEYS = 2; final static String ALGO = "HMACSHA512"; + final static byte[] KDF_RK_HE_INFO = "RelaySMS C2S DR Ratchet v1".getBytes(); public static Pair GENERATE_DH() { SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(); return new Pair<>(securityCurve25519.getPrivateKey(), securityCurve25519.generateKey()); } + /** + * + * @param dhPair This private key (keypair required in Android if supported) + * @param peerPublicKey + * @return + * @throws GeneralSecurityException + * @throws IOException + * @throws InterruptedException + */ + public static byte[] DH_HE( + Pair dhPair, + byte[] peerPublicKey, + byte[] info + ) { + SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(dhPair.first); + return securityCurve25519.calculateSharedSecret( + peerPublicKey, + null, + info + ); + } + /** * * @param dhPair This private key (keypair required in Android if supported) @@ -48,12 +71,26 @@ public static Pair GENERATE_DH() { */ public static byte[] DH(Pair dhPair, byte[] peerPublicKey) { SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(dhPair.first); - return securityCurve25519.calculateSharedSecret(peerPublicKey); + return securityCurve25519.calculateSharedSecret( + peerPublicKey, + null, + "x25591_key_exchange".getBytes() + ); + } + + public static byte[][] KDF_RK_HE( + byte[] rk, + byte[] dhOut + ) throws GeneralSecurityException { + int numKeys = 3; + byte[] info = "SMSWithoutBorders DRHE v2".getBytes(); + return CryptoHelpers.HKDF(ALGO, dhOut, rk, info, HKDF_LEN, numKeys); } public static Pair KDF_RK(byte[] rk, byte[] dhOut) throws GeneralSecurityException { + int numKeys = 2; byte[] info = "KDF_RK".getBytes(); - byte[][] hkdfOutput = CryptoHelpers.HKDF(ALGO, dhOut, rk, info, HKDF_LEN, HKDF_NUM_KEYS); + byte[][] hkdfOutput = CryptoHelpers.HKDF(ALGO, dhOut, rk, info, HKDF_LEN, numKeys); return new Pair<>(hkdfOutput[0], hkdfOutput[1]); } @@ -65,6 +102,24 @@ public static Pair KDF_CK(byte[] ck) throws GeneralSecurityExcep return new Pair<>(_ck, mk); } + public static byte[] HENCRYPT( + byte[] mk, + byte[] plainText + ) throws Throwable { + byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); + byte[] key = new byte[32]; + byte[] authenticationKey = new byte[32]; + byte[] iv = new byte[16]; + + System.arraycopy(hkdfOutput, 0, key, 0, 32); + System.arraycopy(hkdfOutput, 32, authenticationKey, 0, 32); + System.arraycopy(hkdfOutput, 64, iv, 0, 16); + + byte[] cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv); + byte[] mac = buildVerificationHash(authenticationKey, null, cipherText).doFinal(); + return Bytes.concat(cipherText, mac); + } + public static byte[] ENCRYPT(byte[] mk, byte[] plainText, byte[] associated_data) throws Throwable { byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); byte[] key = new byte[32]; @@ -80,6 +135,20 @@ public static byte[] ENCRYPT(byte[] mk, byte[] plainText, byte[] associated_data return Bytes.concat(cipherText, mac); } + public static byte[] HDECRYPT( + byte[] mk, + byte[] cipherText + ) throws Throwable { + cipherText = verifyCipherText(ALGO, mk, cipherText, null); + + byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); + byte[] key = new byte[32]; + byte[] iv = new byte[16]; + System.arraycopy(hkdfOutput, 0, key, 0, 32); + System.arraycopy(hkdfOutput, 64, iv, 0, 16); + + return SecurityAES.decryptAES256CBC(cipherText, key, iv); + } public static byte[] DECRYPT(byte[] mk, byte[] cipherText, byte[] associated_data) throws Throwable { cipherText = verifyCipherText(ALGO, mk, cipherText, associated_data); @@ -92,6 +161,10 @@ public static byte[] DECRYPT(byte[] mk, byte[] cipherText, byte[] associated_dat return SecurityAES.decryptAES256CBC(cipherText, key, iv); } + public static byte[] CONCAT_HE(byte[] AD, byte[] headers) throws IOException { + return Bytes.concat(AD, headers); + } + public static byte[] CONCAT(byte[] AD, Headers headers) throws IOException { return Bytes.concat(AD, headers.getSerialized()); } diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt new file mode 100644 index 0000000..8d93d95 --- /dev/null +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -0,0 +1,213 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.util.Pair +import androidx.core.util.component1 +import androidx.core.util.component2 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.CONCAT_HE +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.DECRYPT +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.ENCRYPT +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.GENERATE_DH +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.HDECRYPT +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.HENCRYPT +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.KDF_CK +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.KDF_RK_HE + +object RatchetsHE { + + const val MAX_SKIP: Int = 100 + + fun ratchetInitAlice( + state: States, + SK: ByteArray, + bobDhPublicKey: ByteArray, + sharedHka: ByteArray, + sharedNhkb: ByteArray, + ) { + state.DHRs = GENERATE_DH() + state.DHRr = bobDhPublicKey + + val kdfRkHEOutputs = KDF_RK_HE(SK, + Protocols.DH_HE( + state.DHRs, + state.DHRr, + Protocols.KDF_RK_HE_INFO + ) + ) + state.RK = kdfRkHEOutputs[0] + state.CKs = kdfRkHEOutputs[1] + state.NHKs = kdfRkHEOutputs[2] + + state.CKr = null + state.Ns = 0 + state.Nr = 0 + state.PN = 0 + state.MKSKIPPED = mutableMapOf() + state.HKs = sharedHka + state.HKr = null + state.NHKr = sharedNhkb + } + + fun ratchetInitBob( + state: States, + SK: ByteArray, + bobDhPublicKeypair: Pair, + sharedHka: ByteArray, + sharedNhkb: ByteArray, + ) { + state.DHRs = bobDhPublicKeypair + state.DHRr = null + state.RK = SK + state.CKs = null + state.CKr = null + state.Ns = 0 + state.Nr = 0 + state.PN = 0 + state.MKSKIPPED = mutableMapOf() + state.HKs = null + state.NHKs = sharedNhkb + state.HKr = null + state.NHKr = sharedHka + } + + fun ratchetEncrypt( + state: States, + plaintext: ByteArray, + AD: ByteArray, + ) : Pair { + val kdfCk = KDF_CK(state.CKs) + state.CKs = kdfCk.first + val mk = kdfCk.second + val header = Headers(state.DHRs, state.PN, state.Ns) + val encHeader = HENCRYPT(state.HKs, header.serialized) + state.Ns += 1 + return Pair(encHeader, + ENCRYPT(mk, plaintext, CONCAT_HE(AD, encHeader))) + } + + fun ratchetDecrypt( + state: States, + encHeader: ByteArray, + cipherText: ByteArray, + AD: ByteArray, + ): ByteArray { + val plaintext = trySkippedMessageKeys(state, encHeader, cipherText, AD) + if(plaintext != null) + return plaintext + + val (header, dhRatchet) = decryptHeader(state, encHeader) + if(dhRatchet) { + skipMessageKeys(state, header.PN) + DHRatchetHE(state, header) + } + + skipMessageKeys(state, header.N) + val kdfCk = KDF_CK(state.CKr) + state.CKr = kdfCk.first + val mk = kdfCk.second + state.Nr += 1 + return DECRYPT(mk, cipherText, CONCAT_HE(AD, encHeader)) + } + + private fun skipMessageKeys( + state: States, + until: Int, + ) { + if(state.Nr + MAX_SKIP < until) + throw Exception("MAX_SKIP Exceeded") + + state.CKr?.let{ + while(state.Nr < until) { + val kdfCk = KDF_CK(state.CKr) + state.CKr = kdfCk.first + val mk = kdfCk.second + state.MKSKIPPED[Pair(state.HKr, state.Nr)] = mk + state.Nr += 1 + } + } + } + + private fun trySkippedMessageKeys( + state: States, + encHeader: ByteArray, + ciphertext: ByteArray, + AD: ByteArray + ) : ByteArray? { + state.MKSKIPPED.forEach { + val hk = it.key.first + val n = it.key.second + val mk = it.value + + val header = HDECRYPT(hk, encHeader).run { + Headers.deSerializeHeader(this) + } + if(header != null && header.N == n) { + state.MKSKIPPED.remove(it.key) + return DECRYPT(mk, ciphertext, CONCAT_HE(AD, encHeader)) + } + } + + return null + } + + private fun decryptHeader( + state: States, + encHeader: ByteArray + ) : Pair { + var header: Headers? = null + try { + header = HDECRYPT(state.HKr, encHeader).run { + Headers.deSerializeHeader(this) + } + } catch(e: Exception) { + e.printStackTrace() + } + + header?.let { + return Pair(header, false) + } + + header = HDECRYPT(state.NHKr, encHeader).run { + Headers.deSerializeHeader(this) + } + header?.let { + return Pair(header, true) + } + throw Exception("Generic error decrypting header...") + } + + private fun DHRatchetHE( + state: States, + header: Headers + ) { + state.PN = state.Ns + state.Ns = 0 + state.Nr = 0 + state.HKs = state.NHKs + state.HKr = state.NHKr + state.DHRr = header.dh + + var kdfRkHEOutputs = KDF_RK_HE(state.RK, + Protocols.DH_HE( + state.DHRs, + state.DHRr, + Protocols.KDF_RK_HE_INFO + ) + ) + state.RK = kdfRkHEOutputs[0] + state.CKr = kdfRkHEOutputs[1] + state.NHKr = kdfRkHEOutputs[2] + + state.DHRs = GENERATE_DH() + + kdfRkHEOutputs = KDF_RK_HE(state.RK, + Protocols.DH_HE( + state.DHRs, + state.DHRr, + Protocols.KDF_RK_HE_INFO + ) + ) + state.RK = kdfRkHEOutputs[0] + state.CKs = kdfRkHEOutputs[1] + state.NHKs = kdfRkHEOutputs[2] + } +} \ No newline at end of file diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.java deleted file mode 100644 index 1625b57..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal; - -import android.util.Log; -import android.util.Pair; -import android.util.Base64; - -import androidx.annotation.Nullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; - -import com.google.gson.JsonSerializer; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.lang.reflect.Type; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class States { - public Pair DHs; - public byte[] DHr; - public byte[] RK; - public byte[] CKs; - public byte[] CKr; - - public int Ns = 0; - public int Nr = 0; - public int PN = 0; - - public Map, byte[]> MKSKIPPED = new HashMap<>(); - - public States(String states) throws JSONException { - if(states == null) - return; - - JSONObject jsonObject = new JSONObject(states); - if(jsonObject.has("DHs")) { - String[] encodedValues = jsonObject.getString("DHs").split(" "); - this.DHs = new Pair<>(android.util.Base64.decode(encodedValues[0], Base64.NO_WRAP), - android.util.Base64.decode(encodedValues[1], Base64.NO_WRAP)); - } - if(jsonObject.has("DHr")) - this.DHr = Base64.decode(jsonObject.getString("DHr"), Base64.NO_WRAP); - - if(jsonObject.has("RK")) - this.RK = Base64.decode(jsonObject.getString("RK"), Base64.NO_WRAP); - if(jsonObject.has("CKs")) - this.CKs = Base64.decode(jsonObject.get("CKs").toString(), Base64.NO_WRAP); - if(jsonObject.has("CKr")) - this.CKr = Base64.decode(jsonObject.getString("CKr"), Base64.NO_WRAP); - this.Ns = jsonObject.getInt("Ns"); - this.Nr = jsonObject.getInt("Nr"); - this.PN = jsonObject.getInt("PN"); - - JSONArray mkskipped = jsonObject.getJSONArray("MKSKIPPED"); - for(int i=0;i(pubkey, pair.getInt(StatesMKSKIPPED.N)), - Base64.decode(pair.getString(StatesMKSKIPPED.MK), Base64.NO_WRAP)); - } - } - - public static byte[] getADForHeaders(States states, Headers headers) { - for(Map.Entry, byte[]> entry : states.MKSKIPPED.entrySet()) { - if(entry.getKey().second == (headers.PN + headers.N)) - return entry.getKey().first; - } - - return null; - } - - public States() { - } - - public String getSerializedStates() { - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(KeyPair.class, new StatesKeyPairSerializer()); - gsonBuilder.registerTypeAdapter(PublicKey.class, new StatesPublicKeySerializer()); - gsonBuilder.registerTypeAdapter(byte[].class, new StatesBytesSerializer()); - gsonBuilder.registerTypeAdapter(Pair.class, new PairStatesBytesSerializer()); - gsonBuilder.registerTypeAdapter(Map.class, new StatesMKSKIPPED()); - gsonBuilder.setPrettyPrinting() - .disableHtmlEscaping(); - - Gson gson = gsonBuilder.create(); - return gson.toJson(this); - } - - @Override - public boolean equals(@Nullable Object obj) { - if(obj instanceof States state) { - return state.getSerializedStates().equals(this.getSerializedStates()); - } - return false; - } - - public static class StatesKeyPairSerializer implements JsonSerializer { - @Override - public JsonElement serialize(KeyPair src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive( - Base64.encodeToString(src.getPublic().getEncoded(), Base64.NO_WRAP)); - } - } - - public static class StatesPublicKeySerializer implements JsonSerializer { - @Override - public JsonElement serialize(PublicKey src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive(Base64.encodeToString(src.getEncoded(), Base64.NO_WRAP)); - } - } - - public static class PairStatesBytesSerializer implements JsonSerializer> { - @Override - public JsonElement serialize(Pair src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive( Base64.encodeToString(src.first, Base64.NO_WRAP) + " " + - Base64.encodeToString(src.second, Base64.NO_WRAP)); - } - } - - public static class StatesBytesSerializer implements JsonSerializer { - @Override - public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { - return new JsonPrimitive( Base64.encodeToString(src, Base64.NO_WRAP)); - } - } - - - public static class StatesMKSKIPPED implements JsonSerializer, byte[]>> { - public final static String PUBLIC_KEY = "PUBLIC_KEY"; - public final static String N = "N"; - public final static String MK = "MK"; - - @Override - public JsonElement serialize(Map, byte[]> src, Type typeOfSrc, JsonSerializationContext context) { - JsonArray jsonArray = new JsonArray(); - for(Map.Entry, byte[]> entry: src.entrySet()) { - String publicKey = Base64.encodeToString(entry.getKey().first, Base64.NO_WRAP); - Integer n = entry.getKey().second; - - JsonObject jsonObject1 = new JsonObject(); - jsonObject1.addProperty(PUBLIC_KEY, publicKey); - jsonObject1.addProperty(N, n); - jsonObject1.addProperty(MK, Base64.encodeToString(entry.getValue(), Base64.NO_WRAP)); - - jsonArray.add(jsonObject1); - } - return jsonArray; - } - } - -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt new file mode 100644 index 0000000..79817ed --- /dev/null +++ b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -0,0 +1,61 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.util.Pair +import kotlinx.serialization.json.Json + +data class States( + @JvmField + var DHs: Pair? = null, + + @JvmField + var DHr: ByteArray? = null, + + @JvmField + var RK: ByteArray? = null, + + @JvmField + var CKs: ByteArray? = null, + + @JvmField + var CKr: ByteArray? = null, + + @JvmField + var Ns: Int = 0, + + @JvmField + var Nr: Int = 0, + + @JvmField + var PN: Int = 0, + + @JvmField + var DHRs: Pair? = null, + + @JvmField + var DHRr: ByteArray? = null, + + @JvmField + var HKs: ByteArray? = null, + + @JvmField + var HKr: ByteArray? = null, + + @JvmField + var NHKs: ByteArray? = null, + + @JvmField + var NHKr: ByteArray? = null, + + @JvmField + var MKSKIPPED: MutableMap, ByteArray> = mutableMapOf() +) { + fun serialize(): String { + return Json.encodeToString(this) + } + + companion object { + fun deserialize(input: String): States { + return Json.decodeFromString(input) + } + } +} \ No newline at end of file From db3edfba76ac7690731dd30afa4d06c530304765 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Sun, 12 Apr 2026 11:42:10 +0100 Subject: [PATCH 04/19] update: basic structure attained --- build.gradle | 99 ++--- double_ratchet/build.gradle | 74 ++++ gradle.properties | 2 + settings.gradle | 13 + .../SecurityAESTest.kt | 21 -- .../SecurityRSATest.java | 54 --- .../SecurityX25519Test.kt | 62 ---- .../libsignal/HeadersTest.kt | 17 - .../libsignal/RatchetsTest.kt | 160 -------- .../libsignal/StateTest.kt | 20 - src/main/AndroidManifest.xml | 7 - .../CryptoHelpers.java | 90 ----- .../EncryptionController.kt | 348 ------------------ .../libsignal_doubleratchet/SecurityAES.java | 91 ----- .../SecurityCurve25519.kt | 118 ------ .../libsignal_doubleratchet/SecurityRSA.kt | 90 ----- .../extensions/context.kt | 146 -------- .../libsignal/Headers.java | 76 ---- .../libsignal/Protocols.java | 173 --------- .../libsignal/Ratchets.java | 119 ------ .../libsignal/RatchetsHE.kt | 213 ----------- .../libsignal/States.kt | 61 --- src/main/res/values/strings.xml | 5 - 23 files changed, 112 insertions(+), 1947 deletions(-) create mode 100644 double_ratchet/build.gradle create mode 100644 gradle.properties create mode 100644 settings.gradle delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt delete mode 100644 src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt delete mode 100644 src/main/AndroidManifest.xml delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.java delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Ratchets.java delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt delete mode 100644 src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt delete mode 100644 src/main/res/values/strings.xml diff --git a/build.gradle b/build.gradle index 607d7c6..9e0ca23 100644 --- a/build.gradle +++ b/build.gradle @@ -1,84 +1,31 @@ -plugins { - id 'com.android.library' -// id 'maven-publish' - id 'signing' - id 'org.jetbrains.kotlin.android' - id "com.vanniktech.maven.publish" version "0.34.0" - id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.10' -} - -android { - namespace 'com.afkanerd.smswithoutborders.libsignal_doubleratchet' - compileSdk 36 - - defaultConfig { - minSdk 24 - targetSdk 36 - - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - aarMetadata { - minCompileSdk = 24 - } +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + ext { +// kotlin_version = '1.8.20-RC' +// kotlin_version = '1.9.23' + kotlin_version = '2.3.10' + agp_version = '8.5.0' + agp_version1 = '8.12.2' } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } - nightly { - } - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_17 - targetCompatibility JavaVersion.VERSION_17 + repositories { + google() + mavenCentral() } + dependencies { + classpath "com.android.tools.build:gradle:$agp_version1" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - testFixtures { - enable = true - } - - kotlinOptions { - jvmTarget = '17' + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files } } -import com.vanniktech.maven.publish.AndroidSingleVariantLibrary -mavenPublishing { - // the first parameter represennts which variant is published - // the second whether to publish a sources jar - // the third whether to publish a javadoc jar - configure(new AndroidSingleVariantLibrary("release", true, true)) +plugins { + // Existing plugins +// alias(libs.plugins.compose.compiler) apply false +// alias(libs.plugins.org.jetbrains.kotlin.android) apply false } - - -dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar', "*.aar"]) - implementation 'androidx.appcompat:appcompat:1.7.0' - implementation 'com.google.guava:guava:33.4.8-jre' - implementation 'com.madgag.spongycastle:prov:1.58.0.0' - implementation 'org.conscrypt:conscrypt-android:2.5.3' - implementation 'androidx.core:core-ktx:1.13.1' - - testImplementation 'junit:junit:4.13.2' - androidTestImplementation 'androidx.test.ext:junit:1.2.1' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' - - implementation 'com.github.netricecake:x25519:2.0' - implementation 'com.google.code.gson:gson:2.11.0' - implementation 'at.favre.lib:hkdf:2.0.0' - - implementation "androidx.datastore:datastore-preferences:1.1.7" - - // optional - RxJava2 support - implementation "androidx.datastore:datastore-preferences-rxjava2:1.1.7" - - // optional - RxJava3 support - implementation "androidx.datastore:datastore-preferences-rxjava3:1.1.7" - - implementation "androidx.datastore:datastore-preferences-core:1.1.7" - - implementation 'com.google.code.gson:gson:2.11.0' - implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0" -} +tasks.register('clean', Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/double_ratchet/build.gradle b/double_ratchet/build.gradle new file mode 100644 index 0000000..d8fd260 --- /dev/null +++ b/double_ratchet/build.gradle @@ -0,0 +1,74 @@ +plugins { + id 'com.android.library' +// id 'maven-publish' + id 'signing' + id 'org.jetbrains.kotlin.android' + id "com.vanniktech.maven.publish" version "0.34.0" + id 'org.jetbrains.kotlin.plugin.serialization' version '2.2.10' +} + +android { + namespace 'com.afkanerd.smswithoutborders.libsignal_doubleratchet' + compileSdk 36 + + defaultConfig { + minSdk 24 + targetSdk 36 + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aarMetadata { + minCompileSdk = 24 + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + nightly { + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + testFixtures { + enable = true + } + + kotlinOptions { + jvmTarget = '17' + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', "*.aar"]) + implementation 'androidx.appcompat:appcompat:1.7.0' + implementation 'com.google.guava:guava:33.4.8-jre' + implementation 'com.madgag.spongycastle:prov:1.58.0.0' + implementation 'org.conscrypt:conscrypt-android:2.5.3' + implementation 'androidx.core:core-ktx:1.13.1' + + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' + + implementation 'com.github.netricecake:x25519:2.0' + implementation 'com.google.code.gson:gson:2.11.0' + implementation 'at.favre.lib:hkdf:2.0.0' + + implementation "androidx.datastore:datastore-preferences:1.1.7" + + // optional - RxJava2 support + implementation "androidx.datastore:datastore-preferences-rxjava2:1.1.7" + + // optional - RxJava3 support + implementation "androidx.datastore:datastore-preferences-rxjava3:1.1.7" + + implementation "androidx.datastore:datastore-preferences-core:1.1.7" + + implementation 'com.google.code.gson:gson:2.11.0' + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0" +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3deb2b0 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +android.useAndroidX=true +org.gradle.jvmargs=-Xmx4096M \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..6e8cd15 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,13 @@ +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven { setUrl("https://jitpack.io") } + } +} +rootProject.name = "lib_signal_double_ratchet_java" +include ':double_ratchet' \ No newline at end of file diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt deleted file mode 100644 index 82f93d4..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import androidx.test.filters.SmallTest -import org.junit.Assert.assertArrayEquals -import org.junit.Test -import javax.crypto.SecretKey - -@SmallTest -class SecurityAESTest { - - @Test - fun aesTest() { - val secretKey = SecurityAES.generateSecretKey(256) - - val input = CryptoHelpers.generateRandomBytes(277) - val cipher = SecurityAES.encryptAES256CBC(input, secretKey.encoded, null) - val output = SecurityAES.decryptAES256CBC(cipher, secretKey.encoded, null) - - assertArrayEquals(input, output) - } -} \ No newline at end of file diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java deleted file mode 100644 index 98487f6..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet; - - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.UnrecoverableEntryException; -import java.security.cert.CertificateException; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -@RunWith(AndroidJUnit4.class) -public class SecurityRSATest { - - String keystoreAlias = "keystoreAlias"; - @Test - public void testCanStoreAndEncrypt() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnrecoverableEntryException, CertificateException, KeyStoreException, IOException { -// KeyPairGenerator kpg = KeyPairGenerator.getInstance( -// KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); -// -// kpg.initialize(new KeyGenParameterSpec.Builder(keystoreAlias, -// KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) -// .setKeySize(2048) -// .setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, -// KeyProperties.DIGEST_SHA512) -// .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) -// .build()); -// -// KeyPair keyPair = kpg.generateKeyPair(); -// PublicKey publicKey = SecurityRSA.generateKeyPair(keystoreAlias, 2048); -// KeyPair keyPair = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias); -// -// SecretKey secretKey = SecurityAES.generateSecretKey(256); -// byte[] cipherText = SecurityRSA.encrypt(keyPair.getPublic(), secretKey.getEncoded()); -// byte[] plainText = SecurityRSA.decrypt(keyPair.getPrivate(), cipherText); -// assertArrayEquals(secretKey.getEncoded(), plainText); - } -} diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt deleted file mode 100644 index b8fa7c2..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.security.keystore.KeyGenParameterSpec -import android.security.keystore.KeyProperties -import androidx.test.filters.SmallTest -import org.junit.Assert.assertArrayEquals -import org.junit.Test -import java.security.KeyPairGenerator -import java.security.KeyStore -import java.security.Signature - -@SmallTest -class SecurityX25519Test { - @Test - fun keystoreEd25519() { - val keystoreAlias = "keystoreAlias" - val kpg: KeyPairGenerator = KeyPairGenerator.getInstance( - KeyProperties.KEY_ALGORITHM_EC, - "AndroidKeyStore" - ) - val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder( - keystoreAlias, - KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY - ).run { - setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) - build() - } - - kpg.initialize(parameterSpec) - val kp = kpg.generateKeyPair() - - val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { - load(null) - } - val entry: KeyStore.Entry = ks.getEntry(keystoreAlias, null) - if (entry !is KeyStore.PrivateKeyEntry) { - throw Exception("No instance of keystore") - } - - val data = "Hello world".encodeToByteArray() - val signature: ByteArray = Signature.getInstance("SHA256withECDSA").run { - initSign(entry.privateKey) - update(data) - sign() - } - - } - - @Test - fun sharedSecret() { - val alice = SecurityCurve25519() - val bob = SecurityCurve25519() - - val alicePubKey = alice.generateKey() - val bobPubKey = bob.generateKey() - - val aliceSharedSecret = alice.calculateSharedSecret(bobPubKey) - val bobSharedSecret = bob.calculateSharedSecret(alicePubKey) - - assertArrayEquals(aliceSharedSecret, bobSharedSecret) - } -} \ No newline at end of file diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt deleted file mode 100644 index e4876ae..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import androidx.test.filters.SmallTest -import junit.framework.TestCase.assertEquals -import org.junit.Test -import java.security.SecureRandom - -@SmallTest -class HeadersTest { - - @Test fun headersTest() { - val header = Headers(SecureRandom.getSeed(32), 0, 0) - val header1 = Headers.deSerializeHeader(header.serialized) - - assertEquals(header, header1) - } -} \ No newline at end of file diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt deleted file mode 100644 index 63c31af..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ /dev/null @@ -1,160 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import android.content.Context -import androidx.core.util.component1 -import androidx.core.util.component2 -import androidx.test.filters.SmallTest -import androidx.test.platform.app.InstrumentationRegistry -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityCurve25519 -import org.junit.Assert.assertArrayEquals -import org.junit.Test -import java.security.SecureRandom - -@SmallTest -class RatchetsTest { - var context: Context = - InstrumentationRegistry.getInstrumentation().targetContext - @Test - fun completeRatchetHETest() { - val aliceEphemeralKeyPair = SecurityCurve25519() - val aliceEphemeralHeaderKeyPair = SecurityCurve25519() - val aliceEphemeralNextHeaderKeyPair = SecurityCurve25519() - - val bobStaticKeyPair = SecurityCurve25519() - val bobEphemeralKeyPair = SecurityCurve25519() - val bobEphemeralHeaderKeyPair = SecurityCurve25519() - val bobEphemeralNextHeaderKeyPair = SecurityCurve25519() - - val aliceNonce = CryptoHelpers.generateRandomBytes(16) - val bobNonce = CryptoHelpers.generateRandomBytes(16) - - val (aliceSk, aliceSkH, aliceSkNh) = SecurityCurve25519(aliceEphemeralKeyPair.privateKey) - .agreeWithAuthAndNonce( - authenticationPublicKey = bobStaticKeyPair.generateKey(), - authenticationPrivateKey = null, - headerPrivateKey = aliceEphemeralHeaderKeyPair.privateKey, - nextHeaderPrivateKey = aliceEphemeralNextHeaderKeyPair.privateKey, - publicKey = bobEphemeralKeyPair.generateKey(), - headerPublicKey = bobEphemeralHeaderKeyPair.generateKey(), - nextHeaderPublicKey = bobEphemeralNextHeaderKeyPair.generateKey(), - salt = "RelaySMS v1".encodeToByteArray(), - nonce1 = aliceNonce, - nonce2 = bobNonce, - info = "RelaySMS C2S DR v1".encodeToByteArray() - ) - - val (bobSk, bobSkH, bobSkNh) = SecurityCurve25519(bobEphemeralKeyPair.privateKey) - .agreeWithAuthAndNonce( - authenticationPublicKey = null, - authenticationPrivateKey = bobStaticKeyPair.privateKey, - headerPrivateKey = bobEphemeralHeaderKeyPair.privateKey, - nextHeaderPrivateKey = bobEphemeralNextHeaderKeyPair.privateKey, - publicKey = aliceEphemeralKeyPair.generateKey(), - headerPublicKey = aliceEphemeralHeaderKeyPair.generateKey(), - nextHeaderPublicKey = aliceEphemeralNextHeaderKeyPair.generateKey(), - salt = "RelaySMS v1".encodeToByteArray(), - nonce1 = aliceNonce, - nonce2 = bobNonce, - info = "RelaySMS C2S DR v1".encodeToByteArray() - ) - - assertArrayEquals(aliceSk, bobSk) - assertArrayEquals(aliceSkH, bobSkH) - assertArrayEquals(aliceSkNh, bobSkNh) - - val aliceState = States() - RatchetsHE.ratchetInitAlice( - state = aliceState, - SK = aliceSk, - bobDhPublicKey = bobEphemeralKeyPair.generateKey(), - sharedHka = aliceSkH, - sharedNhkb = aliceSkNh - ) - - val bobState = States() - RatchetsHE.ratchetInitBob( - state = bobState, - SK = bobSk, - bobDhPublicKeypair = bobEphemeralKeyPair.getKeypair(), - sharedHka = bobSkH, - sharedNhkb = bobSkNh - ) - - val originalText = SecureRandom.getSeed(32); - val (encHeader, aliceCipherText) = RatchetsHE.ratchetEncrypt( - aliceState, - originalText, - bobStaticKeyPair.generateKey() - ) - - var encHeader1: ByteArray? = null - var aliceCipherText1: ByteArray? = null - for(i in 1..10) { - val (encHeader2, aliceCipherText2) = RatchetsHE.ratchetEncrypt( - aliceState, - originalText, - bobStaticKeyPair.generateKey() - ) - encHeader1 = encHeader2 - aliceCipherText1 = aliceCipherText2 - } - - val bobPlainText = RatchetsHE.ratchetDecrypt( - state = bobState, - encHeader = encHeader, - cipherText = aliceCipherText, - AD = bobStaticKeyPair.generateKey() - ) - - val bobPlainText1 = RatchetsHE.ratchetDecrypt( - state = bobState, - encHeader = encHeader1!!, - cipherText = aliceCipherText1!!, - AD = bobStaticKeyPair.generateKey() - ) - - assertArrayEquals(originalText, bobPlainText) - assertArrayEquals(originalText, bobPlainText1) - } - - @Test - fun completeRatchetTest() { - val alice = SecurityCurve25519() - val bob = SecurityCurve25519() - - val SK = alice.calculateSharedSecret(bob.generateKey()) - val SK1 = bob.calculateSharedSecret(alice.generateKey()) - assertArrayEquals(SK, SK1) - - val aliceState = States() - Ratchets.ratchetInitAlice(aliceState, SK, bob.generateKey()) - - val bobState = States() - Ratchets.ratchetInitBob(bobState, SK, bob.getKeypair()) - - val originalText = SecureRandom.getSeed(32); - val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, - bob.generateKey()) - - var header1: Headers? = null - var aliceCipherText1: ByteArray? = null - for(i in 1..10) { - val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, - bob.generateKey()) - header1 = header - aliceCipherText1 = aliceCipherText - } - - val bobPlainText = Ratchets.ratchetDecrypt(bobState, header, aliceCipherText, - bob.generateKey()) - - val bobPlainText1 = Ratchets.ratchetDecrypt(bobState, header1, aliceCipherText1, - bob.generateKey()) - println(bobState.serialize()) - - assertArrayEquals(originalText, bobPlainText) - assertArrayEquals(originalText, bobPlainText1) - } -} - diff --git a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt b/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt deleted file mode 100644 index 42c254e..0000000 --- a/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import androidx.test.filters.SmallTest -import junit.framework.TestCase.assertEquals -import kotlinx.serialization.json.Json -import org.junit.Test -import java.security.SecureRandom - -@SmallTest -class StateTest { - - @Test fun testStates() { - val state = States() - state.DHs = android.util.Pair(SecureRandom.getSeed(32), - SecureRandom.getSeed(32)) - val serializedStates = Json.encodeToString(state) - val deserializedStates = Json.decodeFromString(serializedStates) - assertEquals(state, deserializedStates) - } -} \ No newline at end of file diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml deleted file mode 100644 index 7b53da6..0000000 --- a/src/main/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java deleted file mode 100644 index e84b2af..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoHelpers.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet; - -import com.google.common.primitives.Bytes; - -import java.security.GeneralSecurityException; -import java.security.SecureRandom; -import java.util.Arrays; - -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import at.favre.lib.hkdf.HKDF; - -public class CryptoHelpers { - - public final static String pemStartPrefix = "-----BEGIN PUBLIC KEY-----\n"; - public final static String pemEndPrefix = "\n-----END PUBLIC KEY-----"; - - public static byte[] getCipherMacParameters(String ALGO, byte[] mk) throws GeneralSecurityException { - int hashLen = 80; - byte[] info = "ENCRYPT".getBytes(); - byte[] salt = new byte[hashLen]; - Arrays.fill(salt, (byte) 0); - - return HKDF(ALGO, mk, salt, info, hashLen, 1)[0]; - } - - public static Mac buildVerificationHash(byte[] authKey, byte[] AD, byte[] cipherText) throws GeneralSecurityException { - Mac mac = CryptoHelpers.HMAC256(authKey); - byte[] updatedParams = (AD == null) ? cipherText : Bytes.concat(AD, cipherText); - mac.update(updatedParams); - return mac; - } - - public static byte[] verifyCipherText(String ALGO, byte[] mk, byte[] cipherText, byte[] AD) throws Exception { - final int SHA256_DIGEST_LEN = 32; - - byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); - byte[] key = new byte[32]; - byte[] authenticationKey = new byte[32]; - byte[] iv = new byte[16]; - - System.arraycopy(hkdfOutput, 32, authenticationKey, 0, 32); - - byte[] macValue = new byte[SHA256_DIGEST_LEN]; - System.arraycopy(cipherText, cipherText.length - SHA256_DIGEST_LEN, - macValue, 0, SHA256_DIGEST_LEN); - - byte[] extractedCipherText = new byte[cipherText.length - SHA256_DIGEST_LEN]; - System.arraycopy(cipherText, 0, extractedCipherText, - 0, extractedCipherText.length); - - byte[] reconstructedMac = - buildVerificationHash(authenticationKey, AD, extractedCipherText) - .doFinal(); - if(Arrays.equals(macValue, reconstructedMac)) { - return extractedCipherText; - } - throw new Exception("Cipher signature verification failed"); - } - - public static byte[][] HKDF(String algo, byte[] ikm, byte[] salt, byte[] info, int len, int num) throws GeneralSecurityException { - if (num < 1) - num = 1; - - HKDF hkdf = algo.equals("HMACSHA512") ? HKDF.fromHmacSha512() : HKDF.fromHmacSha256(); - byte[] output = hkdf.extractAndExpand(salt, ikm, info, len * num); - byte[][] outputs = new byte[num][len]; - for (int i = 0; i < num; ++i) { - System.arraycopy(output, i * len, outputs[i], 0, len); - } - return outputs; - } - - public static Mac HMAC256(byte[] data) throws GeneralSecurityException { - String algorithm = "HmacSHA256"; - Mac hmacOutput = Mac.getInstance(algorithm); - SecretKey key = new SecretKeySpec(data, algorithm); - hmacOutput.init(key); - return hmacOutput; - } - - public static byte[] generateRandomBytes(int length) { - SecureRandom random = new SecureRandom(); - byte[] bytes = new byte[length]; - random.nextBytes(bytes); - return bytes; - } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt deleted file mode 100644 index f73bd34..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt +++ /dev/null @@ -1,348 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.content.Context -import android.util.Base64 -import android.widget.Toast -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.core.stringPreferencesKey -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.dataStore -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getEncryptedBinaryData -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getKeypairValues -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.saveBinaryDataEncrypted -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.setKeypairValues -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Headers -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Ratchets -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.States -import com.google.gson.Gson -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import kotlinx.serialization.Serializable - -object EncryptionController { - - @Serializable - enum class SecureRequestMode { - REQUEST_NONE, - REQUEST_REQUESTED, - REQUEST_RECEIVED, - REQUEST_ACCEPTED, - } - - enum class MessageRequestType(val code: Byte) { - TYPE_REQUEST(0x01.toByte()), - TYPE_ACCEPT(0x02.toByte()), - TYPE_MESSAGE(0x03.toByte()); - - companion object { - fun fromCode(code: Byte): MessageRequestType? = - entries.find { it.code == code } // Kotlin 1.9+, use values() before that - - fun fromMessage(message: ByteArray): MessageRequestType? = - entries.find { it.code == message[0] } // Kotlin 1.9+, use values() before that - } - } - - private fun extractRequestPublicKey( publicKey: ByteArray) : ByteArray { - val lenPubKey = publicKey[1].toInt() - return publicKey.drop(2).toByteArray() - } - - private fun extractMessage(data: ByteArray) : Pair { - val lenHeader = data[1].toInt() - val lenMessage = data[2].toInt() - val header = data.copyOfRange(3, 3 + lenHeader) - val message = data.copyOfRange(3 + lenHeader, (3 + lenHeader + lenMessage)) - return Pair(Headers.deSerializeHeader(header), message) - } - - @OptIn(ExperimentalUnsignedTypes::class) - private fun formatRequestPublicKey( - publicKey: ByteArray, - type: MessageRequestType - ) : ByteArray { - val mn = ubyteArrayOf(type.code.toUByte()) - val lenPubKey = ubyteArrayOf(publicKey.size.toUByte()) - - return (mn + lenPubKey).toByteArray() + publicKey - } - - @OptIn(ExperimentalUnsignedTypes::class) - private fun formatMessage( - header: Headers, - cipherText: ByteArray - ) : ByteArray { - val mn = ubyteArrayOf(MessageRequestType.TYPE_MESSAGE.code.toUByte()) - val lenHeader = ubyteArrayOf(header.serialized.size.toUByte()) - val lenMessage = ubyteArrayOf(cipherText.size.toUByte()) - - return (mn + lenHeader + lenMessage).toByteArray() + header.serialized + cipherText - } - - suspend fun sendRequest( - context: Context, - address: String, - mode: SecureRequestMode, - ): ByteArray { - try { - val publicKey = generateIdentityPublicKeys(context, address) - - var type: MessageRequestType? = null - val mode = when(mode) { - SecureRequestMode.REQUEST_RECEIVED -> { - type = MessageRequestType.TYPE_ACCEPT - SecureRequestMode.REQUEST_ACCEPTED - } - else -> { - type = MessageRequestType.TYPE_REQUEST - SecureRequestMode.REQUEST_REQUESTED - } - } - - context.setEncryptionModeStates(address, mode) - return formatRequestPublicKey(publicKey, type) - } catch (e: Exception) { - throw e - } - } - - suspend fun receiveRequest( - context: Context, - address: String, - publicKey: ByteArray, - ) : ByteArray? { - MessageRequestType.fromCode(publicKey[0])?.let { type -> - val publicKey = extractRequestPublicKey(publicKey) - try { - val mode = when(type) { - MessageRequestType.TYPE_REQUEST -> { - SecureRequestMode.REQUEST_RECEIVED - } - MessageRequestType.TYPE_ACCEPT -> { - context.removeEncryptionRatchetStates(address) - SecureRequestMode.REQUEST_ACCEPTED - } - else -> return null - } - context.setEncryptionModeStates( - address, - mode, - publicKey, - ) - } catch (e: Exception) { - throw e - } - return publicKey - } - - return null - } - - @Throws - private suspend fun generateIdentityPublicKeys( - context: Context, - address: String - ): ByteArray { - try { - val libSigCurve25519 = SecurityCurve25519() - val publicKey = libSigCurve25519.generateKey() - context.setKeypairValues(address, publicKey, libSigCurve25519.privateKey) - return publicKey - } catch (e: Exception) { - throw e - } - } - - @Throws - suspend fun decrypt( - context: Context, - address: String, - text: String - ): String? { - - val data = Base64.decode(text, Base64.DEFAULT) - if(MessageRequestType.fromCode(data[0]) != MessageRequestType.TYPE_MESSAGE) - return null - - val payload = try { extractMessage(data) } catch(e: Exception) { - throw e - } - - val modeStates = context.getEncryptionModeStatesSync(address) - val publicKey = Gson().fromJson(modeStates, - SavedEncryptedModes::class.java).publicKey - - if(publicKey == null) { - CoroutineScope(Dispatchers.Main).launch { - Toast.makeText( - context, - context.getString(R.string.missing_public_key), - Toast.LENGTH_LONG).show() - } - return null - } - - val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) - - val keystore = address + "_ratchet_state" - val currentState = context.getEncryptedBinaryData(keystore) - - var state: States? - if(currentState == null) { - state = States() - val sk = context.calculateSharedSecret(address, publicKeyBytes) - val keypair = context.getKeypairValues(address) //public private - - Ratchets.ratchetInitBob( - state, - sk, - android.util.Pair(keypair.second, keypair.first) - ) - } - else state = States.deserialize(String(currentState)) - - val keypair = context.getKeypairValues(address) - var decryptedText: String? - try { - decryptedText = String(Ratchets.ratchetDecrypt( - state, - payload.first, - payload.second, - keypair.first - )) - context.saveBinaryDataEncrypted(keystore, - state.serialize().encodeToByteArray()) - } catch(e: Exception) { - throw e - } - return decryptedText - } - - @Throws - suspend fun encrypt( - context: Context, - address: String, - text: String - ) : String? { - val modeStates = context.getEncryptionModeStatesSync(address) - val publicKey = Gson().fromJson(modeStates, - SavedEncryptedModes::class.java).publicKey - - if(publicKey == null) { - CoroutineScope(Dispatchers.Main).launch { - Toast.makeText( - context, - context.getString(R.string.missing_public_key), - Toast.LENGTH_LONG).show() - } - return null - } - - val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) - - val keystore = address + "_ratchet_state" - val currentState = context.getEncryptedBinaryData(keystore) - - var state: States? - if(currentState == null) { - state = States() - val sk = context.calculateSharedSecret(address, publicKeyBytes) - Ratchets.ratchetInitAlice(state, sk, publicKeyBytes) - } - else state = States.deserialize(String(currentState)) - - val ratchetOutput = Ratchets.ratchetEncrypt(state, - text.encodeToByteArray(), publicKeyBytes) - - return try { - val message = formatMessage( - ratchetOutput.first, - ratchetOutput.second - ) - context.saveBinaryDataEncrypted(keystore, - state.serialize().encodeToByteArray()) - Base64.encodeToString(message, Base64.DEFAULT) - } catch(e: Exception) { - throw e - } - } -} - -private suspend fun Context.calculateSharedSecret( - address: String, - publicKey: ByteArray -): ByteArray? { - val keypair = getKeypairValues(address) //public private - keypair.second?.let { privateKey -> - val libSigCurve25519 = SecurityCurve25519(privateKey) - return libSigCurve25519.calculateSharedSecret(publicKey) - } - return null -} - -data class SavedEncryptedModes( - var mode: EncryptionController.SecureRequestMode, - var publicKey: String? = null, -) - -private suspend fun Context.setEncryptionModeStates( - address: String, - mode: EncryptionController.SecureRequestMode, - publicKey: ByteArray? = null, -) { - val keyValue = stringPreferencesKey(address + "_mode_states") - dataStore.edit { secureComms -> - // Make a mutable copy of existing state - val currentState = secureComms[keyValue] ?: "" - val savedEncryptedModes = if(currentState.isNotEmpty()) Gson() - .fromJson(currentState, SavedEncryptedModes::class.java) - .apply { this.mode = mode } - else SavedEncryptedModes(mode = mode) - - publicKey?.let { publicKey -> - savedEncryptedModes.publicKey = - Base64.encodeToString(publicKey, Base64.DEFAULT) - } - - secureComms[keyValue] = Gson().toJson(savedEncryptedModes) - } -} - -suspend fun Context.removeEncryptionRatchetStates(address: String) { - val keyValue = stringPreferencesKey(address + "_ratchet_state") - dataStore.edit { secureComms -> - secureComms.remove(keyValue) - withContext(Dispatchers.Main) { - Toast.makeText( - this@removeEncryptionRatchetStates, - getString(R.string.ratchet_states_removed), - Toast.LENGTH_LONG).show() - } - } -} - -suspend fun Context.removeEncryptionModeStates(address: String) { - val keyValue = stringPreferencesKey(address + "_mode_states") - dataStore.edit { secureComms -> - secureComms.remove(keyValue) - } -} - -fun Context.getEncryptionRatchetStates(address: String): Flow { - val keyValue = stringPreferencesKey(address + "_ratchet_state") - return dataStore.data.map { it[keyValue] } -} - -suspend fun Context.getEncryptionModeStatesSync(address: String): String? { - val keyValue = stringPreferencesKey(address + "_mode_states") - return dataStore.data.first()[keyValue] -} - -fun Context.getEncryptionModeStates(address: String): Flow { - val keyValue = stringPreferencesKey(address + "_mode_states") - return dataStore.data.map { it[keyValue] } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java deleted file mode 100644 index 30e47a1..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet; - -import android.security.keystore.KeyProperties; - -import com.google.common.primitives.Bytes; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.KeyGenerator; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -public class SecurityAES { - - public static final String DEFAULT_AES_ALGORITHM = "AES/CBC/PKCS5Padding"; - - public static final String ALGORITHM = "AES"; - - public static SecretKey generateSecretKey(int size) throws NoSuchAlgorithmException { - KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES); - keyGenerator.init(size); // Adjust key size as needed - return keyGenerator.generateKey(); - } - - public static byte[] encryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); - aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); - byte[] cipherText = aesCipher.doFinal(data); - - final byte[] IV = aesCipher.getIV(); - byte[] cipherTextIv = new byte[IV.length + cipherText.length]; - System.arraycopy(IV, 0, cipherTextIv, 0, IV.length); - System.arraycopy(cipherText, 0, cipherTextIv, IV.length, cipherText.length); - return cipherTextIv; - } - - public static byte[] decryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { - byte[] iv = new byte[12]; - System.arraycopy(data, 0, iv, 0, iv.length); - - byte[] _data = new byte[data.length - iv.length]; - System.arraycopy(data, iv.length, _data, 0, _data.length); - - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128,iv); - - Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); - aesCipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec); - return aesCipher.doFinal(_data); - } - - public static byte[] encryptAES256CBC(byte[] input, byte[] secretKey, byte[] iv) throws Throwable { - SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, 0, secretKey.length, "AES"); - - Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); - if(iv != null) { - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(input); - } - - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] ciphertext = cipher.doFinal(input); - return Bytes.concat(cipher.getIV(), ciphertext); - } - - public static byte[] decryptAES256CBC(byte[] input, byte[] sharedKey, byte[] iv) throws Throwable { - SecretKeySpec secretKeySpec = new SecretKeySpec(sharedKey, ALGORITHM); - - Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); - if(iv == null) { - iv = new byte[16]; - System.arraycopy(input, 0, iv, 0, 16); - - byte[] content = new byte[input.length - 16]; - System.arraycopy(input, 16, content, 0, content.length); - input = content; - } - - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(input); - } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt deleted file mode 100644 index a4fc59c..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt +++ /dev/null @@ -1,118 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import com.github.netricecake.ecdh.Curve25519 - -class SecurityCurve25519(val privateKey: ByteArray = Curve25519.generateRandomKey()) { - fun generateKey(): ByteArray { - return Curve25519.publicKey(this.privateKey) - } - - private fun agreeWithAuthAndNonceImpl( - authenticationPublicKey: ByteArray?, - authenticationPrivateKey: ByteArray?, - publicKey: ByteArray, - salt: ByteArray, - info: ByteArray, - handshakeSalt: ByteArray, - privateKey: ByteArray? = null, - ): ByteArray { - val privateKey = privateKey ?: this.privateKey - val dh1 = if(authenticationPrivateKey == null) - Curve25519.sharedSecret(privateKey, authenticationPublicKey) - else - Curve25519.sharedSecret(authenticationPrivateKey, publicKey) - val dh2 = Curve25519.sharedSecret(privateKey, publicKey) - var ck = CryptoHelpers.HKDF( - "HMACSHA256", - handshakeSalt, - salt, - info, - 32, - 1 - )[0] - ck = CryptoHelpers.HKDF( - "HMACSHA256", - dh1, - ck, - info, - 32, - 1 - )[0] - return CryptoHelpers.HKDF( - "HMACSHA256", - dh2, - ck, - info, - 32, - 1 - )[0] - } - - fun agreeWithAuthAndNonce( - authenticationPublicKey: ByteArray?, - authenticationPrivateKey: ByteArray?, - headerPrivateKey: ByteArray, - nextHeaderPrivateKey: ByteArray, - publicKey: ByteArray, - headerPublicKey: ByteArray, - nextHeaderPublicKey: ByteArray, - salt: ByteArray, - nonce1: ByteArray, - nonce2: ByteArray, - info: ByteArray, - ): Triple { - val handshakeSalt = nonce1 + nonce2 - val headerInfo = "RelaySMS C2S DRHE v1".encodeToByteArray() - - val rootKey = agreeWithAuthAndNonceImpl( - authenticationPublicKey = authenticationPublicKey, - authenticationPrivateKey = authenticationPrivateKey, - publicKey = publicKey, - salt = salt, - info = info, - handshakeSalt = handshakeSalt, - ) - - val headerKey = agreeWithAuthAndNonceImpl( - authenticationPublicKey = authenticationPublicKey, - authenticationPrivateKey = authenticationPrivateKey, - publicKey = headerPublicKey, - salt = salt, - info = headerInfo, - handshakeSalt = handshakeSalt, - privateKey = headerPrivateKey - ) - - val nextHeaderKey = agreeWithAuthAndNonceImpl( - authenticationPublicKey = authenticationPublicKey, - authenticationPrivateKey = authenticationPrivateKey, - publicKey = nextHeaderPublicKey, - salt = salt, - info = headerInfo, - handshakeSalt = handshakeSalt, - privateKey = nextHeaderPrivateKey - ) - - return Triple(rootKey, headerKey, nextHeaderKey) - } - - fun calculateSharedSecret( - publicKey: ByteArray, - salt: ByteArray? = null, - info: ByteArray? = "x25591_key_exchange".encodeToByteArray(), - ): ByteArray { - val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) - return CryptoHelpers.HKDF( - "HMACSHA256", - sharedKey, - salt, - info, - 32, - 1 - )[0] - } - - fun getKeypair(): android.util.Pair { - return android.util.Pair(privateKey, generateKey()) - } -} \ No newline at end of file diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt deleted file mode 100644 index fa8112d..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.security.keystore.KeyGenParameterSpec -import android.security.keystore.KeyProperties -import java.security.InvalidAlgorithmParameterException -import java.security.InvalidKeyException -import java.security.KeyPairGenerator -import java.security.NoSuchAlgorithmException -import java.security.NoSuchProviderException -import java.security.PrivateKey -import java.security.PublicKey -import java.security.spec.MGF1ParameterSpec -import javax.crypto.BadPaddingException -import javax.crypto.Cipher -import javax.crypto.IllegalBlockSizeException -import javax.crypto.NoSuchPaddingException -import javax.crypto.spec.OAEPParameterSpec -import javax.crypto.spec.PSource - -object SecurityRSA { - var defaultEncryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA256 - var defaultDecryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA1 - - var encryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( - "SHA-256", "MGF1", defaultEncryptionDigest, - PSource.PSpecified.DEFAULT - ) - var decryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( - "SHA-256", "MGF1", defaultDecryptionDigest, - PSource.PSpecified.DEFAULT - ) - - @JvmStatic - @Throws( - NoSuchAlgorithmException::class, - NoSuchProviderException::class, - InvalidAlgorithmParameterException::class - ) - fun generateKeyPair(keystoreAlias: String, keySize: Int = 2048): PublicKey? { - val kpg = KeyPairGenerator.getInstance( - KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore" - ) - kpg.initialize( - KeyGenParameterSpec.Builder( - keystoreAlias, - KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT - ) - .setKeySize(keySize) - .setDigests( - KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, - KeyProperties.DIGEST_SHA512 - ) - .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - .build() - ) - return kpg.generateKeyPair().public - } - - @JvmStatic - @Throws( - NoSuchPaddingException::class, - NoSuchAlgorithmException::class, - IllegalBlockSizeException::class, - BadPaddingException::class, - InvalidKeyException::class, - InvalidAlgorithmParameterException::class - ) - fun decrypt(privateKey: PrivateKey?, data: ByteArray?): ByteArray? { - val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - // cipher.init(Cipher.DECRYPT_MODE, privateKey, decryptionDigestParam); - cipher.init(Cipher.DECRYPT_MODE, privateKey) - return cipher.doFinal(data) - } - - @JvmStatic - @Throws( - NoSuchPaddingException::class, - NoSuchAlgorithmException::class, - IllegalBlockSizeException::class, - BadPaddingException::class, - InvalidKeyException::class, - InvalidAlgorithmParameterException::class - ) - fun encrypt(publicKey: PublicKey?, data: ByteArray?): ByteArray? { - val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - // cipher.init(Cipher.ENCRYPT_MODE, publicKey, encryptionDigestParam); - cipher.init(Cipher.ENCRYPT_MODE, publicKey) - return cipher.doFinal(data) - } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt deleted file mode 100644 index fbc7020..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt +++ /dev/null @@ -1,146 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions - -import android.content.Context -import android.util.Base64 -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.Preferences -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.core.stringPreferencesKey -import androidx.datastore.preferences.core.stringSetPreferencesKey -import androidx.datastore.preferences.preferencesDataStore -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityRSA -import com.google.gson.Gson -import kotlinx.coroutines.flow.first -import java.io.IOException -import java.security.KeyPair -import java.security.KeyStore -import java.security.KeyStoreException -import java.security.NoSuchAlgorithmException -import java.security.UnrecoverableEntryException -import java.security.cert.CertificateException -import javax.crypto.spec.SecretKeySpec - -val Context.dataStore: DataStore by preferencesDataStore(name = "secure_comms") - -/** - * Pair - */ -suspend fun Context.getKeypairValues(address: String): Pair { - val keyValue = stringSetPreferencesKey(address + "_keypair") - val keypairSet = dataStore.data.first()[keyValue] - val encryptionPublicKey = getKeypairFromKeystore(address) - - val publicKey = SecurityRSA.decrypt( - encryptionPublicKey?.private, - Base64.decode(keypairSet?.elementAt(0), Base64.DEFAULT) - ) - val privateKey = SecurityRSA.decrypt( - encryptionPublicKey?.private, - Base64.decode(keypairSet?.elementAt(1), Base64.DEFAULT) - ) - return Pair(publicKey, privateKey) -} - -suspend fun Context.setKeypairValues( - address: String, - publicKey: ByteArray, - privateKey: ByteArray, -) { - val encryptionPublicKey = SecurityRSA.generateKeyPair(address) - - val keyValue = stringSetPreferencesKey(address + "_keypair") - dataStore.edit { secureComms-> - secureComms[keyValue] = setOf( - Base64.encodeToString(publicKey.run { - SecurityRSA.encrypt(encryptionPublicKey, this) - }, Base64.DEFAULT), - Base64.encodeToString(privateKey.run { - SecurityRSA.encrypt(encryptionPublicKey, this) - }, Base64.DEFAULT), - ) - } -} - -@Throws( - KeyStoreException::class, - CertificateException::class, - IOException::class, - NoSuchAlgorithmException::class, - UnrecoverableEntryException::class -) -fun Context.getKeypairFromKeystore(keystoreAlias: String): KeyPair? { - val keyStore = KeyStore.getInstance("AndroidKeyStore") - keyStore.load(null) - - val entry = keyStore.getEntry(keystoreAlias, null) - if (entry is KeyStore.PrivateKeyEntry) { - val privateKey = entry.privateKey - val publicKey = keyStore.getCertificate(keystoreAlias).publicKey - return KeyPair(publicKey, privateKey) - } - return null -} - -data class SavedBinaryData( - val key: ByteArray, - val algorithm: String, - val data: ByteArray, -) - -/** - * Would overwrite anything with the same Keystore Alias - */ -@Throws -suspend fun Context.saveBinaryDataEncrypted( - keystoreAlias: String, - data: ByteArray, -) : Boolean { - val keyValue = stringPreferencesKey(keystoreAlias) - - val aesGcmKey = SecurityAES.generateSecretKey(256) - val data = SecurityAES.encryptAESGCM(data, aesGcmKey) - -// val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias)?.public -// ?: SecurityRSA.generateKeyPair(keystoreAlias) - - var saved = false - dataStore.edit { secureComms-> - try { - val encryptionPublicKey = SecurityRSA.generateKeyPair(keystoreAlias) - SecurityRSA.encrypt(encryptionPublicKey, aesGcmKey.encoded)?.let { key -> - secureComms[keyValue] = Gson().toJson( - SavedBinaryData( - key = key, - algorithm = aesGcmKey.algorithm, - data = data - ) - ) - saved = true - } - } catch(e: Exception) { - throw e - } - } - return saved -} - -@Throws -suspend fun Context.getEncryptedBinaryData(keystoreAlias: String): ByteArray? { - val keyValue = stringPreferencesKey(keystoreAlias) - val data = dataStore.data.first()[keyValue] ?: return null - - val savedBinaryData = Gson().fromJson(data, SavedBinaryData::class.java) - - return try { - val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias) - SecurityRSA.decrypt(encryptionPublicKey?.private, savedBinaryData.key) - ?.run { - SecurityAES.decryptAESGCM(savedBinaryData.data, - SecretKeySpec(this, savedBinaryData.algorithm) - ) - } - } catch(e: Exception) { - throw e - } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.java deleted file mode 100644 index e238589..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal; - -import android.util.Pair; - -import androidx.annotation.Nullable; - -import com.google.common.primitives.Bytes; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; -import java.util.Arrays; - -public class Headers { - - public byte[] dh; - public int PN; - public int N; - - /** - * - * @param dhPair This is a public key - * @param PN - * @param N - */ - public Headers(Pair dhPair, int PN, int N) { - this.dh = dhPair.second; - this.PN = PN; - this.N = N; - } - - public Headers(byte[] dh, int PN, int N) { - this.dh = dh; - this.PN = PN; - this.N = N; - } - - public Headers() {} - - public static Headers deSerializeHeader(byte[] serializedHeader) throws NumberFormatException { - byte[] bytesPN = new byte[4]; - System.arraycopy(serializedHeader, 0, bytesPN, 0, 4); - int PN = ByteBuffer.wrap(bytesPN).order(ByteOrder.LITTLE_ENDIAN).getInt(); - - byte[] bytesN = new byte[4]; - System.arraycopy(serializedHeader, 4, bytesN, 0, 4); - int N = ByteBuffer.wrap(bytesN).order(ByteOrder.LITTLE_ENDIAN).getInt(); - - byte[] pubKey = new byte[serializedHeader.length - 8]; - System.arraycopy(serializedHeader, 8, pubKey, 0, pubKey.length); - - return new Headers(pubKey, PN, N); - } - - @Override - public boolean equals(@Nullable Object obj) { - if(obj instanceof Headers header) { - return Arrays.equals(header.dh, this.dh) && - header.PN == this.PN && - header.N == this.N; - } - return false; - } - - public byte[] getSerialized() throws IOException { - byte[] bytesPN = new byte[4]; - ByteBuffer.wrap(bytesPN).order(ByteOrder.LITTLE_ENDIAN).putInt(this.PN); - - byte[] bytesN = new byte[4]; - ByteBuffer.wrap(bytesN).order(ByteOrder.LITTLE_ENDIAN).putInt(this.N); - - return Bytes.concat(bytesPN, bytesN, this.dh); - } -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java deleted file mode 100644 index 3776adc..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal; - -import static com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers.buildVerificationHash; -import static com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers.getCipherMacParameters; -import static com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers.verifyCipherText; - -import android.util.Pair; - -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers; -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES; -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityCurve25519; -import com.google.common.primitives.Bytes; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; - -import javax.crypto.Mac; - -/** - * This implementations are based on the signal protocols specifications. - * - * This are based on the recommended algorithms and parameters for the encryption - * and decryption. - * - * The goal for this would be to transform it into library which can be used across - * other SMS projects. - * - * ... - */ -public class Protocols { - final static int HKDF_LEN = 32; - final static String ALGO = "HMACSHA512"; - final static byte[] KDF_RK_HE_INFO = "RelaySMS C2S DR Ratchet v1".getBytes(); - - public static Pair GENERATE_DH() { - SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(); - return new Pair<>(securityCurve25519.getPrivateKey(), securityCurve25519.generateKey()); - } - - /** - * - * @param dhPair This private key (keypair required in Android if supported) - * @param peerPublicKey - * @return - * @throws GeneralSecurityException - * @throws IOException - * @throws InterruptedException - */ - public static byte[] DH_HE( - Pair dhPair, - byte[] peerPublicKey, - byte[] info - ) { - SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(dhPair.first); - return securityCurve25519.calculateSharedSecret( - peerPublicKey, - null, - info - ); - } - - /** - * - * @param dhPair This private key (keypair required in Android if supported) - * @param peerPublicKey - * @return - * @throws GeneralSecurityException - * @throws IOException - * @throws InterruptedException - */ - public static byte[] DH(Pair dhPair, byte[] peerPublicKey) { - SecurityCurve25519 securityCurve25519 = new SecurityCurve25519(dhPair.first); - return securityCurve25519.calculateSharedSecret( - peerPublicKey, - null, - "x25591_key_exchange".getBytes() - ); - } - - public static byte[][] KDF_RK_HE( - byte[] rk, - byte[] dhOut - ) throws GeneralSecurityException { - int numKeys = 3; - byte[] info = "SMSWithoutBorders DRHE v2".getBytes(); - return CryptoHelpers.HKDF(ALGO, dhOut, rk, info, HKDF_LEN, numKeys); - } - - public static Pair KDF_RK(byte[] rk, byte[] dhOut) throws GeneralSecurityException { - int numKeys = 2; - byte[] info = "KDF_RK".getBytes(); - byte[][] hkdfOutput = CryptoHelpers.HKDF(ALGO, dhOut, rk, info, HKDF_LEN, numKeys); - return new Pair<>(hkdfOutput[0], hkdfOutput[1]); - } - - public static Pair KDF_CK(byte[] ck) throws GeneralSecurityException { -// Mac mac = CryptoHelpers.HMAC512(ck); - Mac mac = CryptoHelpers.HMAC256(ck); - byte[] _ck = mac.doFinal(new byte[]{0x01}); - byte[] mk = mac.doFinal(new byte[]{0x02}); - return new Pair<>(_ck, mk); - } - - public static byte[] HENCRYPT( - byte[] mk, - byte[] plainText - ) throws Throwable { - byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); - byte[] key = new byte[32]; - byte[] authenticationKey = new byte[32]; - byte[] iv = new byte[16]; - - System.arraycopy(hkdfOutput, 0, key, 0, 32); - System.arraycopy(hkdfOutput, 32, authenticationKey, 0, 32); - System.arraycopy(hkdfOutput, 64, iv, 0, 16); - - byte[] cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv); - byte[] mac = buildVerificationHash(authenticationKey, null, cipherText).doFinal(); - return Bytes.concat(cipherText, mac); - } - - public static byte[] ENCRYPT(byte[] mk, byte[] plainText, byte[] associated_data) throws Throwable { - byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); - byte[] key = new byte[32]; - byte[] authenticationKey = new byte[32]; - byte[] iv = new byte[16]; - - System.arraycopy(hkdfOutput, 0, key, 0, 32); - System.arraycopy(hkdfOutput, 32, authenticationKey, 0, 32); - System.arraycopy(hkdfOutput, 64, iv, 0, 16); - - byte[] cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv); - byte[] mac = buildVerificationHash(authenticationKey, associated_data, cipherText).doFinal(); - return Bytes.concat(cipherText, mac); - } - - public static byte[] HDECRYPT( - byte[] mk, - byte[] cipherText - ) throws Throwable { - cipherText = verifyCipherText(ALGO, mk, cipherText, null); - - byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); - byte[] key = new byte[32]; - byte[] iv = new byte[16]; - System.arraycopy(hkdfOutput, 0, key, 0, 32); - System.arraycopy(hkdfOutput, 64, iv, 0, 16); - - return SecurityAES.decryptAES256CBC(cipherText, key, iv); - } - public static byte[] DECRYPT(byte[] mk, byte[] cipherText, byte[] associated_data) throws Throwable { - cipherText = verifyCipherText(ALGO, mk, cipherText, associated_data); - - byte[] hkdfOutput = getCipherMacParameters(ALGO, mk); - byte[] key = new byte[32]; - byte[] iv = new byte[16]; - System.arraycopy(hkdfOutput, 0, key, 0, 32); - System.arraycopy(hkdfOutput, 64, iv, 0, 16); - - return SecurityAES.decryptAES256CBC(cipherText, key, iv); - } - - public static byte[] CONCAT_HE(byte[] AD, byte[] headers) throws IOException { - return Bytes.concat(AD, headers); - } - - public static byte[] CONCAT(byte[] AD, Headers headers) throws IOException { - return Bytes.concat(AD, headers.getSerialized()); - } - -} - diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Ratchets.java b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Ratchets.java deleted file mode 100644 index 36e03cf..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Ratchets.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal; - -import android.util.Pair; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.Arrays; - -public class Ratchets { - public static final int MAX_SKIP = 100; - - /** - * - * @param state - * @param SK - * @param dhPublicKeyBob - * @throws GeneralSecurityException - * @throws IOException - * @throws InterruptedException - */ - public static void ratchetInitAlice(States state, - byte[] SK, - byte[] dhPublicKeyBob) throws GeneralSecurityException, IOException, InterruptedException { - state.DHs = Protocols.GENERATE_DH(); - state.DHr = dhPublicKeyBob; - byte[] dh_out = Protocols.DH(state.DHs, state.DHr); - Pair kdfRkOutput = Protocols.KDF_RK(SK, dh_out); - state.RK = kdfRkOutput.first; - state.CKs = kdfRkOutput.second; - } - - public static void ratchetInitBob(States state, byte[] SK, Pair dhKeyPairBob) { - state.DHs = dhKeyPairBob; - state.RK = SK; - } - - public static Pair ratchetEncrypt(States state, byte[] plainText, byte[] AD) throws Throwable { - Pair kdfCkOutput = Protocols.KDF_CK(state.CKs); - state.CKs = kdfCkOutput.first; - byte[] mk = kdfCkOutput.second; - Headers header = new Headers(state.DHs, state.PN, state.Ns); - state.Ns += 1; - - byte[] cipherText = Protocols.ENCRYPT(mk, plainText, Protocols.CONCAT(AD, header)); - return new Pair<>(header, cipherText); - } - - /** - * - * @param state - * @param header - * @param cipherText - * @param AD - * @return - * @throws Throwable - */ - public static byte[] ratchetDecrypt(States state, - Headers header, - byte[] cipherText, - byte[] AD) throws Throwable { - byte[] plainText = trySkippedMessageKeys(state, header, cipherText, AD); - if(plainText != null) - return plainText; - - if(state.DHr == null || !Arrays.equals(header.dh, state.DHr)) { - skipMessageKeys(state, header.PN); - DHRatchet(state, header); - } - skipMessageKeys(state, header.N); - Pair kdfCkOutput = Protocols.KDF_CK(state.CKr); - state.CKr = kdfCkOutput.first; - byte[] mk = kdfCkOutput.second; - state.Nr += 1; - return Protocols.DECRYPT(mk, cipherText, Protocols.CONCAT(AD, header)); - } - - private static void DHRatchet(States state, Headers header) throws GeneralSecurityException, IOException, InterruptedException { - state.PN = state.Ns; - state.Ns = 0; - state.Nr = 0; - state.DHr = header.dh; - byte[] dh_out = Protocols.DH(state.DHs, state.DHr); - Pair kdfRkOutput = Protocols.KDF_RK(state.RK, dh_out); - state.RK = kdfRkOutput.first; - state.CKr = kdfRkOutput.second; - - state.DHs = Protocols.GENERATE_DH(); - kdfRkOutput = Protocols.KDF_RK(state.RK, Protocols.DH(state.DHs, state.DHr)); - state.RK = kdfRkOutput.first; - state.CKs = kdfRkOutput.second; - } - - private static byte[] trySkippedMessageKeys(States state, Headers header, byte[] cipherText, byte[] AD) throws Throwable { - Pair mkSkippedKeys = new Pair<>(header.dh, header.N); - if(state.MKSKIPPED.containsKey(mkSkippedKeys)){ - byte[] mk = state.MKSKIPPED.get(mkSkippedKeys); - state.MKSKIPPED.remove(mkSkippedKeys); - return Protocols.DECRYPT(mk, cipherText, Protocols.CONCAT(AD, header)); - } - return null; - } - - private static void skipMessageKeys(States state, int until) throws Exception { - if((state.Nr + MAX_SKIP) < until) { - throw new Exception("MAX skip exceeded"); - } - - if(state.CKr != null) { - while(state.Nr < until) { - Pair kdfCkOutput = Protocols.KDF_CK(state.CKr); - state.CKr = kdfCkOutput.first; - byte[] mk = kdfCkOutput.second; - state.MKSKIPPED.put(new Pair<>(state.DHr, state.Nr), mk); - state.Nr +=1; - } - } - } - -} diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt deleted file mode 100644 index 8d93d95..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ /dev/null @@ -1,213 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import android.util.Pair -import androidx.core.util.component1 -import androidx.core.util.component2 -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.CONCAT_HE -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.DECRYPT -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.ENCRYPT -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.GENERATE_DH -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.HDECRYPT -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.HENCRYPT -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.KDF_CK -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols.KDF_RK_HE - -object RatchetsHE { - - const val MAX_SKIP: Int = 100 - - fun ratchetInitAlice( - state: States, - SK: ByteArray, - bobDhPublicKey: ByteArray, - sharedHka: ByteArray, - sharedNhkb: ByteArray, - ) { - state.DHRs = GENERATE_DH() - state.DHRr = bobDhPublicKey - - val kdfRkHEOutputs = KDF_RK_HE(SK, - Protocols.DH_HE( - state.DHRs, - state.DHRr, - Protocols.KDF_RK_HE_INFO - ) - ) - state.RK = kdfRkHEOutputs[0] - state.CKs = kdfRkHEOutputs[1] - state.NHKs = kdfRkHEOutputs[2] - - state.CKr = null - state.Ns = 0 - state.Nr = 0 - state.PN = 0 - state.MKSKIPPED = mutableMapOf() - state.HKs = sharedHka - state.HKr = null - state.NHKr = sharedNhkb - } - - fun ratchetInitBob( - state: States, - SK: ByteArray, - bobDhPublicKeypair: Pair, - sharedHka: ByteArray, - sharedNhkb: ByteArray, - ) { - state.DHRs = bobDhPublicKeypair - state.DHRr = null - state.RK = SK - state.CKs = null - state.CKr = null - state.Ns = 0 - state.Nr = 0 - state.PN = 0 - state.MKSKIPPED = mutableMapOf() - state.HKs = null - state.NHKs = sharedNhkb - state.HKr = null - state.NHKr = sharedHka - } - - fun ratchetEncrypt( - state: States, - plaintext: ByteArray, - AD: ByteArray, - ) : Pair { - val kdfCk = KDF_CK(state.CKs) - state.CKs = kdfCk.first - val mk = kdfCk.second - val header = Headers(state.DHRs, state.PN, state.Ns) - val encHeader = HENCRYPT(state.HKs, header.serialized) - state.Ns += 1 - return Pair(encHeader, - ENCRYPT(mk, plaintext, CONCAT_HE(AD, encHeader))) - } - - fun ratchetDecrypt( - state: States, - encHeader: ByteArray, - cipherText: ByteArray, - AD: ByteArray, - ): ByteArray { - val plaintext = trySkippedMessageKeys(state, encHeader, cipherText, AD) - if(plaintext != null) - return plaintext - - val (header, dhRatchet) = decryptHeader(state, encHeader) - if(dhRatchet) { - skipMessageKeys(state, header.PN) - DHRatchetHE(state, header) - } - - skipMessageKeys(state, header.N) - val kdfCk = KDF_CK(state.CKr) - state.CKr = kdfCk.first - val mk = kdfCk.second - state.Nr += 1 - return DECRYPT(mk, cipherText, CONCAT_HE(AD, encHeader)) - } - - private fun skipMessageKeys( - state: States, - until: Int, - ) { - if(state.Nr + MAX_SKIP < until) - throw Exception("MAX_SKIP Exceeded") - - state.CKr?.let{ - while(state.Nr < until) { - val kdfCk = KDF_CK(state.CKr) - state.CKr = kdfCk.first - val mk = kdfCk.second - state.MKSKIPPED[Pair(state.HKr, state.Nr)] = mk - state.Nr += 1 - } - } - } - - private fun trySkippedMessageKeys( - state: States, - encHeader: ByteArray, - ciphertext: ByteArray, - AD: ByteArray - ) : ByteArray? { - state.MKSKIPPED.forEach { - val hk = it.key.first - val n = it.key.second - val mk = it.value - - val header = HDECRYPT(hk, encHeader).run { - Headers.deSerializeHeader(this) - } - if(header != null && header.N == n) { - state.MKSKIPPED.remove(it.key) - return DECRYPT(mk, ciphertext, CONCAT_HE(AD, encHeader)) - } - } - - return null - } - - private fun decryptHeader( - state: States, - encHeader: ByteArray - ) : Pair { - var header: Headers? = null - try { - header = HDECRYPT(state.HKr, encHeader).run { - Headers.deSerializeHeader(this) - } - } catch(e: Exception) { - e.printStackTrace() - } - - header?.let { - return Pair(header, false) - } - - header = HDECRYPT(state.NHKr, encHeader).run { - Headers.deSerializeHeader(this) - } - header?.let { - return Pair(header, true) - } - throw Exception("Generic error decrypting header...") - } - - private fun DHRatchetHE( - state: States, - header: Headers - ) { - state.PN = state.Ns - state.Ns = 0 - state.Nr = 0 - state.HKs = state.NHKs - state.HKr = state.NHKr - state.DHRr = header.dh - - var kdfRkHEOutputs = KDF_RK_HE(state.RK, - Protocols.DH_HE( - state.DHRs, - state.DHRr, - Protocols.KDF_RK_HE_INFO - ) - ) - state.RK = kdfRkHEOutputs[0] - state.CKr = kdfRkHEOutputs[1] - state.NHKr = kdfRkHEOutputs[2] - - state.DHRs = GENERATE_DH() - - kdfRkHEOutputs = KDF_RK_HE(state.RK, - Protocols.DH_HE( - state.DHRs, - state.DHRr, - Protocols.KDF_RK_HE_INFO - ) - ) - state.RK = kdfRkHEOutputs[0] - state.CKs = kdfRkHEOutputs[1] - state.NHKs = kdfRkHEOutputs[2] - } -} \ No newline at end of file diff --git a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt deleted file mode 100644 index 79817ed..0000000 --- a/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import android.util.Pair -import kotlinx.serialization.json.Json - -data class States( - @JvmField - var DHs: Pair? = null, - - @JvmField - var DHr: ByteArray? = null, - - @JvmField - var RK: ByteArray? = null, - - @JvmField - var CKs: ByteArray? = null, - - @JvmField - var CKr: ByteArray? = null, - - @JvmField - var Ns: Int = 0, - - @JvmField - var Nr: Int = 0, - - @JvmField - var PN: Int = 0, - - @JvmField - var DHRs: Pair? = null, - - @JvmField - var DHRr: ByteArray? = null, - - @JvmField - var HKs: ByteArray? = null, - - @JvmField - var HKr: ByteArray? = null, - - @JvmField - var NHKs: ByteArray? = null, - - @JvmField - var NHKr: ByteArray? = null, - - @JvmField - var MKSKIPPED: MutableMap, ByteArray> = mutableMapOf() -) { - fun serialize(): String { - return Json.encodeToString(this) - } - - companion object { - fun deserialize(input: String): States { - return Json.decodeFromString(input) - } - } -} \ No newline at end of file diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml deleted file mode 100644 index e8057bf..0000000 --- a/src/main/res/values/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - SMSWithoutBorders DoubleRatchet LibSignal - Missing public key - Ratchet states removed - \ No newline at end of file From 955b5d0a9f32d4cd9f043e80b88779ac8571b6eb Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Sun, 12 Apr 2026 17:17:59 +0100 Subject: [PATCH 05/19] update: basic structure attained --- .gitignore | 39 +- double_ratchet/build.gradle | 27 +- .../SecurityAESTest.kt | 20 + .../SecurityRSATest.java | 54 +++ .../SecurityX25519Test.kt | 62 ++++ .../libsignal/HeadersTest.kt | 17 + .../libsignal/RatchetsTest.kt | 159 ++++++++ .../libsignal/StateTest.kt | 20 + double_ratchet/src/main/AndroidManifest.xml | 7 + .../libsignal_doubleratchet/CryptoUtils.kt | 35 ++ .../EncryptionController.kt | 348 ++++++++++++++++++ .../libsignal_doubleratchet/SecurityAES.java | 91 +++++ .../SecurityCurve25519.kt | 115 ++++++ .../libsignal_doubleratchet/SecurityRSA.kt | 90 +++++ .../extensions/context.kt | 154 ++++++++ .../libsignal/Headers.kt | 37 ++ .../libsignal/Protocols.kt | 175 +++++++++ .../libsignal/RatchetsHE.kt | 213 +++++++++++ .../libsignal/States.kt | 37 ++ .../src/main/res/values/strings.xml | 9 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 45457 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 251 +++++++++++++ gradlew.bat | 94 +++++ 24 files changed, 2046 insertions(+), 15 deletions(-) create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt create mode 100644 double_ratchet/src/main/AndroidManifest.xml create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt create mode 100644 double_ratchet/src/main/res/values/strings.xml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat diff --git a/.gitignore b/.gitignore index 42afabf..dde283f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,38 @@ -/build \ No newline at end of file +*.iml +.gradle +/local.properties +/.idea/* +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +double_ratchet/build/* +double_ratchet/build/ +double_ratchet/build +/captures +.externalNativeBuild +.cxx +*.aab +*.apk +local.properties +keystore.properties +*.jks +ks.passwd +venv/* +/release.properties +*.sw* +gradle.properties +*.tmp.sh +*.logs +/double_ratchet/.idea/.gitignore +/double_ratchet/.ideadouble_ratchetInsightsSettings.xml +/double_ratchet/.idea/caches/deviceStreaming.xml +/double_ratchet/.idea/gradle.xml +/double_ratchet/.idea/migrations.xml +/double_ratchet/.idea/misc.xml +/double_ratchet/.idea/runConfigurations.xml +/double_ratchet/.idea/vcs.xml \ No newline at end of file diff --git a/double_ratchet/build.gradle b/double_ratchet/build.gradle index d8fd260..aedd88b 100644 --- a/double_ratchet/build.gradle +++ b/double_ratchet/build.gradle @@ -45,30 +45,29 @@ android { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar', "*.aar"]) - implementation 'androidx.appcompat:appcompat:1.7.0' - implementation 'com.google.guava:guava:33.4.8-jre' - implementation 'com.madgag.spongycastle:prov:1.58.0.0' + implementation 'androidx.appcompat:appcompat:1.7.1' + implementation 'com.google.guava:guava:33.5.0-jre' implementation 'org.conscrypt:conscrypt-android:2.5.3' - implementation 'androidx.core:core-ktx:1.13.1' + implementation 'androidx.core:core-ktx:1.18.0' testImplementation 'junit:junit:4.13.2' - androidTestImplementation 'androidx.test.ext:junit:1.2.1' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' + androidTestImplementation 'androidx.test.ext:junit:1.3.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0' - implementation 'com.github.netricecake:x25519:2.0' - implementation 'com.google.code.gson:gson:2.11.0' + implementation 'com.google.code.gson:gson:2.13.2' implementation 'at.favre.lib:hkdf:2.0.0' - implementation "androidx.datastore:datastore-preferences:1.1.7" + implementation "androidx.datastore:datastore-preferences:1.2.1" // optional - RxJava2 support - implementation "androidx.datastore:datastore-preferences-rxjava2:1.1.7" + implementation "androidx.datastore:datastore-preferences-rxjava2:1.2.1" // optional - RxJava3 support - implementation "androidx.datastore:datastore-preferences-rxjava3:1.1.7" + implementation "androidx.datastore:datastore-preferences-rxjava3:1.2.1" - implementation "androidx.datastore:datastore-preferences-core:1.1.7" + implementation "androidx.datastore:datastore-preferences-core:1.2.1" - implementation 'com.google.code.gson:gson:2.11.0' - implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0" + implementation 'com.google.code.gson:gson:2.13.2' + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0" + implementation("org.bouncycastle:bcprov-jdk18on:1.83") } diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt new file mode 100644 index 0000000..ced6619 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt @@ -0,0 +1,20 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import androidx.test.filters.SmallTest +import org.junit.Assert.assertArrayEquals +import org.junit.Test + +@SmallTest +class SecurityAESTest { + + @Test + fun aesTest() { + val secretKey = SecurityAES.generateSecretKey(256) + + val input = CryptoUtils.generateRandomBytes(277) + val cipher = SecurityAES.encryptAES256CBC(input, secretKey.encoded, null) + val output = SecurityAES.decryptAES256CBC(cipher, secretKey.encoded, null) + + assertArrayEquals(input, output) + } +} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java new file mode 100644 index 0000000..98487f6 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java @@ -0,0 +1,54 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet; + + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.UnrecoverableEntryException; +import java.security.cert.CertificateException; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; + +@RunWith(AndroidJUnit4.class) +public class SecurityRSATest { + + String keystoreAlias = "keystoreAlias"; + @Test + public void testCanStoreAndEncrypt() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnrecoverableEntryException, CertificateException, KeyStoreException, IOException { +// KeyPairGenerator kpg = KeyPairGenerator.getInstance( +// KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); +// +// kpg.initialize(new KeyGenParameterSpec.Builder(keystoreAlias, +// KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) +// .setKeySize(2048) +// .setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, +// KeyProperties.DIGEST_SHA512) +// .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) +// .build()); +// +// KeyPair keyPair = kpg.generateKeyPair(); +// PublicKey publicKey = SecurityRSA.generateKeyPair(keystoreAlias, 2048); +// KeyPair keyPair = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias); +// +// SecretKey secretKey = SecurityAES.generateSecretKey(256); +// byte[] cipherText = SecurityRSA.encrypt(keyPair.getPublic(), secretKey.getEncoded()); +// byte[] plainText = SecurityRSA.decrypt(keyPair.getPrivate(), cipherText); +// assertArrayEquals(secretKey.getEncoded(), plainText); + } +} diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt new file mode 100644 index 0000000..b8fa7c2 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt @@ -0,0 +1,62 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import androidx.test.filters.SmallTest +import org.junit.Assert.assertArrayEquals +import org.junit.Test +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.Signature + +@SmallTest +class SecurityX25519Test { + @Test + fun keystoreEd25519() { + val keystoreAlias = "keystoreAlias" + val kpg: KeyPairGenerator = KeyPairGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_EC, + "AndroidKeyStore" + ) + val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder( + keystoreAlias, + KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY + ).run { + setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) + build() + } + + kpg.initialize(parameterSpec) + val kp = kpg.generateKeyPair() + + val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { + load(null) + } + val entry: KeyStore.Entry = ks.getEntry(keystoreAlias, null) + if (entry !is KeyStore.PrivateKeyEntry) { + throw Exception("No instance of keystore") + } + + val data = "Hello world".encodeToByteArray() + val signature: ByteArray = Signature.getInstance("SHA256withECDSA").run { + initSign(entry.privateKey) + update(data) + sign() + } + + } + + @Test + fun sharedSecret() { + val alice = SecurityCurve25519() + val bob = SecurityCurve25519() + + val alicePubKey = alice.generateKey() + val bobPubKey = bob.generateKey() + + val aliceSharedSecret = alice.calculateSharedSecret(bobPubKey) + val bobSharedSecret = bob.calculateSharedSecret(alicePubKey) + + assertArrayEquals(aliceSharedSecret, bobSharedSecret) + } +} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt new file mode 100644 index 0000000..744e6b9 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt @@ -0,0 +1,17 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import androidx.test.filters.SmallTest +import junit.framework.TestCase.assertEquals +import org.junit.Test +import java.security.SecureRandom + +@SmallTest +class HeadersTest { + + @Test fun headersTest() { + val header = Headers(SecureRandom.getSeed(32), 0, 0) + val header1 = Headers.deserialize(header.serialized) + + assertEquals(header, header1) + } +} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt new file mode 100644 index 0000000..4cd94b0 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -0,0 +1,159 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.content.Context +import androidx.test.filters.SmallTest +import androidx.test.platform.app.InstrumentationRegistry +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityCurve25519 +import org.junit.Assert.assertArrayEquals +import org.junit.Test +import java.security.SecureRandom + +@SmallTest +class RatchetsTest { + var context: Context = + InstrumentationRegistry.getInstrumentation().targetContext + @Test + fun completeRatchetHETest() { + val aliceEphemeralKeyPair = SecurityCurve25519() + val aliceEphemeralHeaderKeyPair = SecurityCurve25519() + val aliceEphemeralNextHeaderKeyPair = SecurityCurve25519() + + val bobStaticKeyPair = SecurityCurve25519() + val bobEphemeralKeyPair = SecurityCurve25519() + val bobEphemeralHeaderKeyPair = SecurityCurve25519() + val bobEphemeralNextHeaderKeyPair = SecurityCurve25519() + + val aliceNonce = CryptoUtils.generateRandomBytes(16) + val bobNonce = CryptoUtils.generateRandomBytes(16) + + val (aliceSk, aliceSkH, aliceSkNh) = SecurityCurve25519(aliceEphemeralKeyPair.privateKey) + .agreeWithAuthAndNonce( + authenticationPublicKey = bobStaticKeyPair.generateKey(), + authenticationPrivateKey = null, + headerPrivateKey = aliceEphemeralHeaderKeyPair.privateKey, + nextHeaderPrivateKey = aliceEphemeralNextHeaderKeyPair.privateKey, + publicKey = bobEphemeralKeyPair.generateKey(), + headerPublicKey = bobEphemeralHeaderKeyPair.generateKey(), + nextHeaderPublicKey = bobEphemeralNextHeaderKeyPair.generateKey(), + salt = context.getString(R.string.dr_salt).encodeToByteArray(), + nonce1 = aliceNonce, + nonce2 = bobNonce, + info = context.getString(R.string.dr_info).encodeToByteArray() + ) + + val (bobSk, bobSkH, bobSkNh) = SecurityCurve25519(bobEphemeralKeyPair.privateKey) + .agreeWithAuthAndNonce( + authenticationPublicKey = null, + authenticationPrivateKey = bobStaticKeyPair.privateKey, + headerPrivateKey = bobEphemeralHeaderKeyPair.privateKey, + nextHeaderPrivateKey = bobEphemeralNextHeaderKeyPair.privateKey, + publicKey = aliceEphemeralKeyPair.generateKey(), + headerPublicKey = aliceEphemeralHeaderKeyPair.generateKey(), + nextHeaderPublicKey = aliceEphemeralNextHeaderKeyPair.generateKey(), + salt = context.getString(R.string.dr_salt).encodeToByteArray(), + nonce1 = aliceNonce, + nonce2 = bobNonce, + info = context.getString(R.string.dr_info).encodeToByteArray() + ) + + assertArrayEquals(aliceSk, bobSk) + assertArrayEquals(aliceSkH, bobSkH) + assertArrayEquals(aliceSkNh, bobSkNh) + + val aliceState = States() + RatchetsHE.ratchetInitAlice( + state = aliceState, + SK = aliceSk, + bobDhPublicKey = bobEphemeralKeyPair.generateKey(), + sharedHka = aliceSkH, + sharedNhkb = aliceSkNh + ) + + val bobState = States() + RatchetsHE.ratchetInitBob( + state = bobState, + SK = bobSk, + bobDhPublicKeypair = bobEphemeralKeyPair.getKeypair(), + sharedHka = bobSkH, + sharedNhkb = bobSkNh + ) + + val originalText = SecureRandom.getSeed(32); + val (encHeader, aliceCipherText) = RatchetsHE.ratchetEncrypt( + aliceState, + originalText, + bobStaticKeyPair.generateKey() + ) + + var encHeader1: ByteArray? = null + var aliceCipherText1: ByteArray? = null + for(i in 1..10) { + val (encHeader2, aliceCipherText2) = RatchetsHE.ratchetEncrypt( + aliceState, + originalText, + bobStaticKeyPair.generateKey() + ) + encHeader1 = encHeader2 + aliceCipherText1 = aliceCipherText2 + } + + val bobPlainText = RatchetsHE.ratchetDecrypt( + state = bobState, + encHeader = encHeader, + cipherText = aliceCipherText, + AD = bobStaticKeyPair.generateKey() + ) + + val bobPlainText1 = RatchetsHE.ratchetDecrypt( + state = bobState, + encHeader = encHeader1!!, + cipherText = aliceCipherText1!!, + AD = bobStaticKeyPair.generateKey() + ) + + assertArrayEquals(originalText, bobPlainText) + assertArrayEquals(originalText, bobPlainText1) + } + + @Test + fun completeRatchetTest() { + val alice = SecurityCurve25519() + val bob = SecurityCurve25519() + + val SK = alice.calculateSharedSecret(bob.generateKey()) + val SK1 = bob.calculateSharedSecret(alice.generateKey()) + assertArrayEquals(SK, SK1) + + val aliceState = States() + Ratchets.ratchetInitAlice(aliceState, SK, bob.generateKey()) + + val bobState = States() + Ratchets.ratchetInitBob(bobState, SK, bob.getKeypair()) + + val originalText = SecureRandom.getSeed(32); + val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, + bob.generateKey()) + + var header1: Headers? = null + var aliceCipherText1: ByteArray? = null + for(i in 1..10) { + val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, + bob.generateKey()) + header1 = header + aliceCipherText1 = aliceCipherText + } + + val bobPlainText = Ratchets.ratchetDecrypt(bobState, header, aliceCipherText, + bob.generateKey()) + + val bobPlainText1 = Ratchets.ratchetDecrypt(bobState, header1, aliceCipherText1, + bob.generateKey()) + println(bobState.serialize()) + + assertArrayEquals(originalText, bobPlainText) + assertArrayEquals(originalText, bobPlainText1) + } +} + diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt new file mode 100644 index 0000000..42c254e --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt @@ -0,0 +1,20 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import androidx.test.filters.SmallTest +import junit.framework.TestCase.assertEquals +import kotlinx.serialization.json.Json +import org.junit.Test +import java.security.SecureRandom + +@SmallTest +class StateTest { + + @Test fun testStates() { + val state = States() + state.DHs = android.util.Pair(SecureRandom.getSeed(32), + SecureRandom.getSeed(32)) + val serializedStates = Json.encodeToString(state) + val deserializedStates = Json.decodeFromString(serializedStates) + assertEquals(state, deserializedStates) + } +} \ No newline at end of file diff --git a/double_ratchet/src/main/AndroidManifest.xml b/double_ratchet/src/main/AndroidManifest.xml new file mode 100644 index 0000000..7b53da6 --- /dev/null +++ b/double_ratchet/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt new file mode 100644 index 0000000..8060e1d --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -0,0 +1,35 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import at.favre.lib.hkdf.HKDF +import com.google.common.primitives.Bytes +import java.security.GeneralSecurityException +import java.security.SecureRandom +import javax.crypto.Mac +import javax.crypto.SecretKey +import javax.crypto.spec.SecretKeySpec + +object CryptoUtils { + fun hkdf( + ikm: ByteArray, + salt: ByteArray?, + info: ByteArray?, + len: Int, + ): ByteArray { + return HKDF.fromHmacSha512() + .extractAndExpand( + salt, + ikm, + info, + len + ) + } + + fun hmac(data: ByteArray?): Mac { + val algorithm = "HmacSHA512" + val output = Mac.getInstance(algorithm) + val key: SecretKey = SecretKeySpec(data, algorithm) + output.init(key) + return output + } + +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt new file mode 100644 index 0000000..a72bed4 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt @@ -0,0 +1,348 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import android.content.Context +import android.util.Base64 +import android.widget.Toast +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.dataStore +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getEncryptedBinaryData +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getKeypairValues +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.saveBinaryDataEncrypted +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.setKeypairValues +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Headers +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Ratchets +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.States +import com.google.gson.Gson +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable + +object EncryptionController { + + @Serializable + enum class SecureRequestMode { + REQUEST_NONE, + REQUEST_REQUESTED, + REQUEST_RECEIVED, + REQUEST_ACCEPTED, + } + + enum class MessageRequestType(val code: Byte) { + TYPE_REQUEST(0x01.toByte()), + TYPE_ACCEPT(0x02.toByte()), + TYPE_MESSAGE(0x03.toByte()); + + companion object { + fun fromCode(code: Byte): MessageRequestType? = + entries.find { it.code == code } // Kotlin 1.9+, use values() before that + + fun fromMessage(message: ByteArray): MessageRequestType? = + entries.find { it.code == message[0] } // Kotlin 1.9+, use values() before that + } + } + + private fun extractRequestPublicKey( publicKey: ByteArray) : ByteArray { + val lenPubKey = publicKey[1].toInt() + return publicKey.drop(2).toByteArray() + } + + private fun extractMessage(data: ByteArray) : Pair { + val lenHeader = data[1].toInt() + val lenMessage = data[2].toInt() + val header = data.copyOfRange(3, 3 + lenHeader) + val message = data.copyOfRange(3 + lenHeader, (3 + lenHeader + lenMessage)) + return Pair(Headers.deserialize(header), message) + } + + @OptIn(ExperimentalUnsignedTypes::class) + private fun formatRequestPublicKey( + publicKey: ByteArray, + type: MessageRequestType + ) : ByteArray { + val mn = ubyteArrayOf(type.code.toUByte()) + val lenPubKey = ubyteArrayOf(publicKey.size.toUByte()) + + return (mn + lenPubKey).toByteArray() + publicKey + } + + @OptIn(ExperimentalUnsignedTypes::class) + private fun formatMessage( + header: Headers, + cipherText: ByteArray + ) : ByteArray { + val mn = ubyteArrayOf(MessageRequestType.TYPE_MESSAGE.code.toUByte()) + val lenHeader = ubyteArrayOf(header.serialized.size.toUByte()) + val lenMessage = ubyteArrayOf(cipherText.size.toUByte()) + + return (mn + lenHeader + lenMessage).toByteArray() + header.serialized + cipherText + } + + suspend fun sendRequest( + context: Context, + address: String, + mode: SecureRequestMode, + ): ByteArray { + try { + val publicKey = generateIdentityPublicKeys(context, address) + + var type: MessageRequestType? = null + val mode = when(mode) { + SecureRequestMode.REQUEST_RECEIVED -> { + type = MessageRequestType.TYPE_ACCEPT + SecureRequestMode.REQUEST_ACCEPTED + } + else -> { + type = MessageRequestType.TYPE_REQUEST + SecureRequestMode.REQUEST_REQUESTED + } + } + + context.setEncryptionModeStates(address, mode) + return formatRequestPublicKey(publicKey, type) + } catch (e: Exception) { + throw e + } + } + + suspend fun receiveRequest( + context: Context, + address: String, + publicKey: ByteArray, + ) : ByteArray? { + MessageRequestType.fromCode(publicKey[0])?.let { type -> + val publicKey = extractRequestPublicKey(publicKey) + try { + val mode = when(type) { + MessageRequestType.TYPE_REQUEST -> { + SecureRequestMode.REQUEST_RECEIVED + } + MessageRequestType.TYPE_ACCEPT -> { + context.removeEncryptionRatchetStates(address) + SecureRequestMode.REQUEST_ACCEPTED + } + else -> return null + } + context.setEncryptionModeStates( + address, + mode, + publicKey, + ) + } catch (e: Exception) { + throw e + } + return publicKey + } + + return null + } + + @Throws + private suspend fun generateIdentityPublicKeys( + context: Context, + address: String + ): ByteArray { + try { + val libSigCurve25519 = SecurityCurve25519() + val publicKey = libSigCurve25519.generateKey() + context.setKeypairValues(address, publicKey, libSigCurve25519.privateKey) + return publicKey + } catch (e: Exception) { + throw e + } + } + + @Throws + suspend fun decrypt( + context: Context, + address: String, + text: String + ): String? { + + val data = Base64.decode(text, Base64.DEFAULT) + if(MessageRequestType.fromCode(data[0]) != MessageRequestType.TYPE_MESSAGE) + return null + + val payload = try { extractMessage(data) } catch(e: Exception) { + throw e + } + + val modeStates = context.getEncryptionModeStatesSync(address) + val publicKey = Gson().fromJson(modeStates, + SavedEncryptedModes::class.java).publicKey + + if(publicKey == null) { + CoroutineScope(Dispatchers.Main).launch { + Toast.makeText( + context, + context.getString(R.string.missing_public_key), + Toast.LENGTH_LONG).show() + } + return null + } + + val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) + + val keystore = address + "_ratchet_state" + val currentState = context.getEncryptedBinaryData(keystore) + + var state: States? + if(currentState == null) { + state = States() + val sk = context.calculateSharedSecret(address, publicKeyBytes) + val keypair = context.getKeypairValues(address) //public private + + Ratchets.ratchetInitBob( + state, + sk, + android.util.Pair(keypair.second, keypair.first) + ) + } + else state = States.deserialize(String(currentState)) + + val keypair = context.getKeypairValues(address) + var decryptedText: String? + try { + decryptedText = String(Ratchets.ratchetDecrypt( + state, + payload.first, + payload.second, + keypair.first + )) + context.saveBinaryDataEncrypted(keystore, + state.serialize().encodeToByteArray()) + } catch(e: Exception) { + throw e + } + return decryptedText + } + + @Throws + suspend fun encrypt( + context: Context, + address: String, + text: String + ) : String? { + val modeStates = context.getEncryptionModeStatesSync(address) + val publicKey = Gson().fromJson(modeStates, + SavedEncryptedModes::class.java).publicKey + + if(publicKey == null) { + CoroutineScope(Dispatchers.Main).launch { + Toast.makeText( + context, + context.getString(R.string.missing_public_key), + Toast.LENGTH_LONG).show() + } + return null + } + + val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) + + val keystore = address + "_ratchet_state" + val currentState = context.getEncryptedBinaryData(keystore) + + var state: States? + if(currentState == null) { + state = States() + val sk = context.calculateSharedSecret(address, publicKeyBytes) + Ratchets.ratchetInitAlice(state, sk, publicKeyBytes) + } + else state = States.deserialize(String(currentState)) + + val ratchetOutput = Ratchets.ratchetEncrypt(state, + text.encodeToByteArray(), publicKeyBytes) + + return try { + val message = formatMessage( + ratchetOutput.first, + ratchetOutput.second + ) + context.saveBinaryDataEncrypted(keystore, + state.serialize().encodeToByteArray()) + Base64.encodeToString(message, Base64.DEFAULT) + } catch(e: Exception) { + throw e + } + } +} + +private suspend fun Context.calculateSharedSecret( + address: String, + publicKey: ByteArray +): ByteArray? { + val keypair = getKeypairValues(address) //public private + keypair.second?.let { privateKey -> + val libSigCurve25519 = SecurityCurve25519(privateKey) + return libSigCurve25519.calculateSharedSecret(publicKey) + } + return null +} + +data class SavedEncryptedModes( + var mode: EncryptionController.SecureRequestMode, + var publicKey: String? = null, +) + +private suspend fun Context.setEncryptionModeStates( + address: String, + mode: EncryptionController.SecureRequestMode, + publicKey: ByteArray? = null, +) { + val keyValue = stringPreferencesKey(address + "_mode_states") + dataStore.edit { secureComms -> + // Make a mutable copy of existing state + val currentState = secureComms[keyValue] ?: "" + val savedEncryptedModes = if(currentState.isNotEmpty()) Gson() + .fromJson(currentState, SavedEncryptedModes::class.java) + .apply { this.mode = mode } + else SavedEncryptedModes(mode = mode) + + publicKey?.let { publicKey -> + savedEncryptedModes.publicKey = + Base64.encodeToString(publicKey, Base64.DEFAULT) + } + + secureComms[keyValue] = Gson().toJson(savedEncryptedModes) + } +} + +suspend fun Context.removeEncryptionRatchetStates(address: String) { + val keyValue = stringPreferencesKey(address + "_ratchet_state") + dataStore.edit { secureComms -> + secureComms.remove(keyValue) + withContext(Dispatchers.Main) { + Toast.makeText( + this@removeEncryptionRatchetStates, + getString(R.string.ratchet_states_removed), + Toast.LENGTH_LONG).show() + } + } +} + +suspend fun Context.removeEncryptionModeStates(address: String) { + val keyValue = stringPreferencesKey(address + "_mode_states") + dataStore.edit { secureComms -> + secureComms.remove(keyValue) + } +} + +fun Context.getEncryptionRatchetStates(address: String): Flow { + val keyValue = stringPreferencesKey(address + "_ratchet_state") + return dataStore.data.map { it[keyValue] } +} + +suspend fun Context.getEncryptionModeStatesSync(address: String): String? { + val keyValue = stringPreferencesKey(address + "_mode_states") + return dataStore.data.first()[keyValue] +} + +fun Context.getEncryptionModeStates(address: String): Flow { + val keyValue = stringPreferencesKey(address + "_mode_states") + return dataStore.data.map { it[keyValue] } +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java new file mode 100644 index 0000000..30e47a1 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java @@ -0,0 +1,91 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet; + +import android.security.keystore.KeyProperties; + +import com.google.common.primitives.Bytes; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +public class SecurityAES { + + public static final String DEFAULT_AES_ALGORITHM = "AES/CBC/PKCS5Padding"; + + public static final String ALGORITHM = "AES"; + + public static SecretKey generateSecretKey(int size) throws NoSuchAlgorithmException { + KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES); + keyGenerator.init(size); // Adjust key size as needed + return keyGenerator.generateKey(); + } + + public static byte[] encryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); + aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); + byte[] cipherText = aesCipher.doFinal(data); + + final byte[] IV = aesCipher.getIV(); + byte[] cipherTextIv = new byte[IV.length + cipherText.length]; + System.arraycopy(IV, 0, cipherTextIv, 0, IV.length); + System.arraycopy(cipherText, 0, cipherTextIv, IV.length, cipherText.length); + return cipherTextIv; + } + + public static byte[] decryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { + byte[] iv = new byte[12]; + System.arraycopy(data, 0, iv, 0, iv.length); + + byte[] _data = new byte[data.length - iv.length]; + System.arraycopy(data, iv.length, _data, 0, _data.length); + + GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128,iv); + + Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); + aesCipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec); + return aesCipher.doFinal(_data); + } + + public static byte[] encryptAES256CBC(byte[] input, byte[] secretKey, byte[] iv) throws Throwable { + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, 0, secretKey.length, "AES"); + + Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); + if(iv != null) { + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); + return cipher.doFinal(input); + } + + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + byte[] ciphertext = cipher.doFinal(input); + return Bytes.concat(cipher.getIV(), ciphertext); + } + + public static byte[] decryptAES256CBC(byte[] input, byte[] sharedKey, byte[] iv) throws Throwable { + SecretKeySpec secretKeySpec = new SecretKeySpec(sharedKey, ALGORITHM); + + Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); + if(iv == null) { + iv = new byte[16]; + System.arraycopy(input, 0, iv, 0, 16); + + byte[] content = new byte[input.length - 16]; + System.arraycopy(input, 16, content, 0, content.length); + input = content; + } + + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); + return cipher.doFinal(input); + } +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt new file mode 100644 index 0000000..9f3bc28 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt @@ -0,0 +1,115 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import android.content.Context +import android.util.Pair +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.EphemeralKeyPair +import org.bouncycastle.math.ec.custom.djb.Curve25519 + + +class SecurityCurve25519(context: Context) : Protocols(context) { + + private fun generateKey( + ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationPublicKey: CipherParameters, + ephemeralPublicKey: CipherParameters, + salt: ByteArray, + info: ByteArray, + handshakeSalt: ByteArray, + ) { + val dh1 = dh(ephemeralKeyPair, authenticationPublicKey) + val dh2 = dh(ephemeralKeyPair, ephemeralPublicKey) + return CryptoUtils.hkdf( + handshakeSalt, + salt, + info, + 32, + ).run { + CryptoUtils.hkdf( + dh1, + this, + info, + 32, + ).run { + CryptoUtils.hkdf( + dh2, + this, + info, + 32, + ) + } + } + } + + fun agreeWithAuthAndNonce( + e: AsymmetricCipherKeyPair, + s: CipherParameters, + he: CipherParameters, + hne: CipherParameters, + salt: ByteArray, + nonce1: ByteArray, + nonce2: ByteArray, + info: ByteArray, + hInfo: ByteArray, + ): Triple { + val handshakeSalt = nonce1 + nonce2 + val rootKey = generateKey( + ephemeralKeyPair = ephemeralKeyPair, + authenticationPublicKey = authenticationPublicKey, + publicKey = TODO(), + salt = TODO(), + info = TODO(), + handshakeSalt = TODO() + ) + + val headerKey = agreeWithAuthAndNonceImpl( + authenticationPublicKey = authenticationPublicKey, + authenticationPrivateKey = authenticationPrivateKey, + publicKey = headerPublicKey, + salt = salt, + info = headerInfo, + handshakeSalt = handshakeSalt, + privateKey = headerPrivateKey + ) + + val nextHeaderKey = agreeWithAuthAndNonceImpl( + authenticationPublicKey = authenticationPublicKey, + authenticationPrivateKey = authenticationPrivateKey, + publicKey = nextHeaderPublicKey, + salt = salt, + info = headerInfo, + handshakeSalt = handshakeSalt, + privateKey = nextHeaderPrivateKey + ) + + return Triple(rootKey, headerKey, nextHeaderKey) + } + + fun calculateSharedSecret( + publicKey: ByteArray, + ): ByteArray { + return Curve25519.sharedSecret(this.privateKey, publicKey) + } + + fun calculateSharedSecret( + publicKey: ByteArray, + salt: ByteArray? = null, + info: ByteArray? = "x25591_key_exchange".encodeToByteArray(), + ): ByteArray { + val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) + return CryptoUtils.hkdf( + "HMACSHA256", + sharedKey, + salt, + info, + 32, + 1 + )[0] + } + + fun getKeypair(): Pair { + return Pair(privateKey, generateKey()) + } +} \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt new file mode 100644 index 0000000..fa8112d --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt @@ -0,0 +1,90 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.InvalidAlgorithmParameterException +import java.security.InvalidKeyException +import java.security.KeyPairGenerator +import java.security.NoSuchAlgorithmException +import java.security.NoSuchProviderException +import java.security.PrivateKey +import java.security.PublicKey +import java.security.spec.MGF1ParameterSpec +import javax.crypto.BadPaddingException +import javax.crypto.Cipher +import javax.crypto.IllegalBlockSizeException +import javax.crypto.NoSuchPaddingException +import javax.crypto.spec.OAEPParameterSpec +import javax.crypto.spec.PSource + +object SecurityRSA { + var defaultEncryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA256 + var defaultDecryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA1 + + var encryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( + "SHA-256", "MGF1", defaultEncryptionDigest, + PSource.PSpecified.DEFAULT + ) + var decryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( + "SHA-256", "MGF1", defaultDecryptionDigest, + PSource.PSpecified.DEFAULT + ) + + @JvmStatic + @Throws( + NoSuchAlgorithmException::class, + NoSuchProviderException::class, + InvalidAlgorithmParameterException::class + ) + fun generateKeyPair(keystoreAlias: String, keySize: Int = 2048): PublicKey? { + val kpg = KeyPairGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore" + ) + kpg.initialize( + KeyGenParameterSpec.Builder( + keystoreAlias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setKeySize(keySize) + .setDigests( + KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, + KeyProperties.DIGEST_SHA512 + ) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) + .build() + ) + return kpg.generateKeyPair().public + } + + @JvmStatic + @Throws( + NoSuchPaddingException::class, + NoSuchAlgorithmException::class, + IllegalBlockSizeException::class, + BadPaddingException::class, + InvalidKeyException::class, + InvalidAlgorithmParameterException::class + ) + fun decrypt(privateKey: PrivateKey?, data: ByteArray?): ByteArray? { + val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) + // cipher.init(Cipher.DECRYPT_MODE, privateKey, decryptionDigestParam); + cipher.init(Cipher.DECRYPT_MODE, privateKey) + return cipher.doFinal(data) + } + + @JvmStatic + @Throws( + NoSuchPaddingException::class, + NoSuchAlgorithmException::class, + IllegalBlockSizeException::class, + BadPaddingException::class, + InvalidKeyException::class, + InvalidAlgorithmParameterException::class + ) + fun encrypt(publicKey: PublicKey?, data: ByteArray?): ByteArray? { + val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) + // cipher.init(Cipher.ENCRYPT_MODE, publicKey, encryptionDigestParam); + cipher.init(Cipher.ENCRYPT_MODE, publicKey) + return cipher.doFinal(data) + } +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt new file mode 100644 index 0000000..d970fd9 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt @@ -0,0 +1,154 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions + +import android.content.Context +import android.util.Base64 +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.core.stringSetPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityRSA +import com.google.gson.Gson +import kotlinx.coroutines.flow.first +import java.io.IOException +import java.security.KeyPair +import java.security.KeyStore +import java.security.KeyStoreException +import java.security.NoSuchAlgorithmException +import java.security.SecureRandom +import java.security.UnrecoverableEntryException +import java.security.cert.CertificateException +import javax.crypto.spec.SecretKeySpec + +val Context.dataStore: DataStore by preferencesDataStore(name = "secure_comms") + +/** + * Pair + */ +suspend fun Context.getKeypairValues(address: String): Pair { + val keyValue = stringSetPreferencesKey(address + "_keypair") + val keypairSet = dataStore.data.first()[keyValue] + val encryptionPublicKey = getKeypairFromKeystore(address) + + val publicKey = SecurityRSA.decrypt( + encryptionPublicKey?.private, + Base64.decode(keypairSet?.elementAt(0), Base64.DEFAULT) + ) + val privateKey = SecurityRSA.decrypt( + encryptionPublicKey?.private, + Base64.decode(keypairSet?.elementAt(1), Base64.DEFAULT) + ) + return Pair(publicKey, privateKey) +} + +suspend fun Context.setKeypairValues( + address: String, + publicKey: ByteArray, + privateKey: ByteArray, +) { + val encryptionPublicKey = SecurityRSA.generateKeyPair(address) + + val keyValue = stringSetPreferencesKey(address + "_keypair") + dataStore.edit { secureComms-> + secureComms[keyValue] = setOf( + Base64.encodeToString(publicKey.run { + SecurityRSA.encrypt(encryptionPublicKey, this) + }, Base64.DEFAULT), + Base64.encodeToString(privateKey.run { + SecurityRSA.encrypt(encryptionPublicKey, this) + }, Base64.DEFAULT), + ) + } +} + +@Throws( + KeyStoreException::class, + CertificateException::class, + IOException::class, + NoSuchAlgorithmException::class, + UnrecoverableEntryException::class +) +fun Context.getKeypairFromKeystore(keystoreAlias: String): KeyPair? { + val keyStore = KeyStore.getInstance("AndroidKeyStore") + keyStore.load(null) + + val entry = keyStore.getEntry(keystoreAlias, null) + if (entry is KeyStore.PrivateKeyEntry) { + val privateKey = entry.privateKey + val publicKey = keyStore.getCertificate(keystoreAlias).publicKey + return KeyPair(publicKey, privateKey) + } + return null +} + +data class SavedBinaryData( + val key: ByteArray, + val algorithm: String, + val data: ByteArray, +) + +/** + * Would overwrite anything with the same Keystore Alias + */ +@Throws +suspend fun Context.saveBinaryDataEncrypted( + keystoreAlias: String, + data: ByteArray, +) : Boolean { + val keyValue = stringPreferencesKey(keystoreAlias) + + val aesGcmKey = SecurityAES.generateSecretKey(256) + val data = SecurityAES.encryptAESGCM(data, aesGcmKey) + +// val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias)?.public +// ?: SecurityRSA.generateKeyPair(keystoreAlias) + + var saved = false + dataStore.edit { secureComms-> + try { + val encryptionPublicKey = SecurityRSA.generateKeyPair(keystoreAlias) + SecurityRSA.encrypt(encryptionPublicKey, aesGcmKey.encoded)?.let { key -> + secureComms[keyValue] = Gson().toJson( + SavedBinaryData( + key = key, + algorithm = aesGcmKey.algorithm, + data = data + ) + ) + saved = true + } + } catch(e: Exception) { + throw e + } + } + return saved +} + +@Throws +suspend fun Context.getEncryptedBinaryData(keystoreAlias: String): ByteArray? { + val keyValue = stringPreferencesKey(keystoreAlias) + val data = dataStore.data.first()[keyValue] ?: return null + + val savedBinaryData = Gson().fromJson(data, SavedBinaryData::class.java) + + return try { + val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias) + SecurityRSA.decrypt(encryptionPublicKey?.private, savedBinaryData.key) + ?.run { + SecurityAES.decryptAESGCM(savedBinaryData.data, + SecretKeySpec(this, savedBinaryData.algorithm) + ) + } + } catch(e: Exception) { + throw e + } +} + +fun Context.generateRandomBytes(length: Int): ByteArray { + val random = SecureRandom() + val bytes = ByteArray(length) + random.nextBytes(bytes) + return bytes +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt new file mode 100644 index 0000000..f37fde8 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt @@ -0,0 +1,37 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import com.google.common.primitives.Bytes +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.params.X25519PublicKeyParameters +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.KeyPair + +class Headers(var dh: AsymmetricCipherKeyPair, pn: UByte, n: UByte) { + var pn: UByte = 0u + var n: UByte = 0u + + init { + this.pn = pn + this.n = n + } + + val serialized: ByteArray + get() { + val pk = dh.public as X25519PublicKeyParameters + return byteArrayOf(pn.toByte()) + byteArrayOf(n.toByte()) + pk.encoded + } + + companion object { + fun deserialize(header: ByteArray): Headers { + val pn = header[0].toUByte() + val n = header[1].toUByte() + val pk = header.sliceArray(2 until header.size) + return Headers( + AsymmetricCipherKeyPair( + X25519PublicKeyParameters(pk, 0), + null + ), pn, n) + } + } +} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt new file mode 100644 index 0000000..ff7ad07 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -0,0 +1,175 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.content.Context +import android.util.Pair +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hkdf +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hmac +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES +import com.google.common.primitives.Bytes +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.agreement.X25519Agreement +import org.bouncycastle.crypto.generators.X25519KeyPairGenerator +import org.bouncycastle.crypto.params.X25519KeyGenerationParameters +import org.bouncycastle.jce.provider.BouncyCastleProvider +import java.security.SecureRandom +import java.security.Security + +/** + * This implementations are based on the signal protocols specifications. + * + * This are based on the recommended algorithms and parameters for the encryption + * and decryption. + * + * The goal for this would be to transform it into library which can be used across + * other SMS projects. + * + * [...](https://signal.org/docs/specifications/doubleratchet/) + */ +open class Protocols(private val context: Context) { + + init { + Security.removeProvider("BC") + Security.addProvider(BouncyCastleProvider()) + } + + fun generateDH(): AsymmetricCipherKeyPair { + val generator = X25519KeyPairGenerator() + generator.init(X25519KeyGenerationParameters(SecureRandom())) + return generator.generateKeyPair() + } + + fun dh(keypair: AsymmetricCipherKeyPair, publicKey: CipherParameters): ByteArray { + val sharedSecret = ByteArray(32) + val agreement = X25519Agreement() + agreement.init(keypair.private) + agreement.calculateAgreement(publicKey, sharedSecret, 0) + return sharedSecret + } + + fun kdfRk( + rk: ByteArray, + dhOut: ByteArray + ): Triple { + val info = context.getString(R.string.dr_rk_info).encodeToByteArray() + return hkdf(dhOut, rk, info, 32*3).run { + Triple( + this.sliceArray(0 until 32), + this.sliceArray(32 until 64), + this.sliceArray(64 until 96), + ) + } + } + + fun kdfCk(ck: ByteArray?): Pair { + if(ck == null) throw Exception("CK came in null! Terminating") + + val mac = hmac(ck) + val newCk = mac.doFinal(byteArrayOf(0x01)) + val mk = mac.doFinal(byteArrayOf(0x02)) + return Pair(newCk, mk) + } + + fun encrypt( + mk: ByteArray, + plainText: ByteArray, + ad: ByteArray, + ): ByteArray { + val len = 80 + return hkdf( + ikm = mk, + salt = ByteArray(len), + info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), + len = len, + ).run { + val key = this.sliceArray(0 until 32) + val authKey = this.sliceArray(32 until 64) + val iv = this.sliceArray(64 until 80) + + val cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv) + val mac = hmac(authKey) + mac.update(ad + cipherText) + cipherText + mac.doFinal() + } + } + + fun hEncrypt( + mk: ByteArray, + plainText: ByteArray, + ): ByteArray { + val len = 80 + return hkdf( + ikm = mk, + salt = ByteArray(len), + info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), + len = len, + ).run { + val key = this.sliceArray(0 until 32) + val authKey = this.sliceArray(32 until 64) + val iv = this.sliceArray(64 until 80) + + val cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv) + + val mac = hmac(authKey) + mac.update(cipherText) + cipherText + mac.doFinal() + } + } + + fun decrypt(mk: ByteArray, cipherText: ByteArray, ad: ByteArray): ByteArray { + val len = 80 + return hkdf( + ikm = mk, + salt = ByteArray(len), + info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), + len = len, + ).run { + val authKey = this.sliceArray(32 until 64) + val cipherText = cipherText.dropLast(32).toByteArray() + + val mac = hmac(authKey) + mac.update(ad + cipherText) + + val incomingMac = cipherText.takeLast(32).toByteArray() + if(!incomingMac.contentEquals(mac.doFinal())) { + throw Exception("Message failed authentication") + } + + val key = this.sliceArray(0 until 32) + val iv = this.sliceArray(64 until 80) + SecurityAES.decryptAES256CBC(cipherText, key, iv) + } + } + + fun hDecrypt(mk: ByteArray, cipherText: ByteArray): ByteArray { + val len = 80 + return hkdf( + ikm = mk, + salt = ByteArray(len), + info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), + len = len, + ).run { + val authKey = this.sliceArray(32 until 64) + val cipherText = cipherText.dropLast(32).toByteArray() + + val mac = hmac(authKey) + mac.update(cipherText) + + val incomingMac = cipherText.takeLast(32).toByteArray() + if(!incomingMac.contentEquals(mac.doFinal())) { + throw Exception("Message failed authentication") + } + + val key = this.sliceArray(0 until 32) + val iv = this.sliceArray(64 until 80) + SecurityAES.decryptAES256CBC(cipherText, key, iv) + } + } + + fun concat(ad: ByteArray, headers: ByteArray): ByteArray { + return ad + headers + } +} + diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt new file mode 100644 index 0000000..eb30786 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -0,0 +1,213 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.content.Context +import android.util.Pair +import androidx.core.util.component1 +import androidx.core.util.component2 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.params.X25519PublicKeyParameters + +class RatchetPayload( + val header: ByteArray, + val cipherText: ByteArray, +) + +class RatchetsHE(context: Context) : Protocols(context){ + val MAX_SKIP = 255 + + /** + * @param state + * @param sk + * @param bobDhPublicKey + * @param sharedHka Alice's shared header key + * @param sharedNHka Alice's next shared header key + */ + fun ratchetInitAlice( + state: States, + sk: ByteArray, + bobDhPublicKey: CipherParameters, + sharedHka: ByteArray, + sharedNHka: ByteArray, + ) { + state.DHRs = generateDH() + state.DHRr = bobDhPublicKey + + kdfRk( + rk = sk, dh( state.DHRs!!, state.DHRr!!) + ).let { + state.RK = it.first + state.CKs = it.second + state.NHKs = it.third + } + + state.CKr = null + state.Ns = 0u + state.Nr = 0u + state.PN = 0u + state.MKSKIPPED = mutableMapOf() + state.HKs = sharedHka + state.HKr = null + state.NHKr = sharedNHka + } + + fun ratchetInitBob( + state: States, + sk: ByteArray, + bobDhPublicKeypair: AsymmetricCipherKeyPair, + sharedHka: ByteArray, + sharedNHka: ByteArray, + ) { + state.DHRs = bobDhPublicKeypair + state.DHRr = null + state.RK = sk + state.CKs = null + state.CKr = null + state.Ns = 0u + state.Nr = 0u + state.PN = 0u + state.MKSKIPPED = mutableMapOf() + state.HKs = null + state.NHKs = sharedNHka + state.HKr = null + state.NHKr = sharedHka + } + + fun ratchetEncrypt( + state: States, + plaintext: ByteArray, + ad: ByteArray, + ) : RatchetPayload { + val (ck, mk) = kdfCk(state.CKs) + state.CKs = ck + val header = Headers(state.DHRs!!, state.PN, state.Ns) + val encHeader = hEncrypt(state.HKs!!, header.serialized) + state.Ns++ + return RatchetPayload( + header = encHeader, + cipherText = encrypt(mk, plaintext, concat(ad, encHeader)) + ) + } + + fun ratchetDecrypt( + state: States, + encHeader: ByteArray, + cipherText: ByteArray, + ad: ByteArray, + ): ByteArray { + val plaintext = trySkippedMessageKeys(state, encHeader, cipherText, ad) + if(plaintext != null) + return plaintext + + val (header, dhRatchet) = decryptHeader(state, encHeader) + if(dhRatchet) { + skipMessageKeys(state, header.pn.toInt()) + dhRatchet(state, header) + } + + skipMessageKeys(state, header.n.toInt()) + val kdfCk = kdfCk(state.CKr) + state.CKr = kdfCk.first + val mk = kdfCk.second + state.Nr++ + return decrypt(mk, cipherText, concat(ad, encHeader)) + } + + private fun skipMessageKeys( + state: States, + until: Int, + ) { + if(state.Nr.toInt() + MAX_SKIP < until) + throw Exception("MAX SKIP Exceeded") + + state.CKr?.let{ + while(state.Nr.toInt() < until) { + val kdfCk = kdfCk(state.CKr) + state.CKr = kdfCk.first + val mk = kdfCk.second + state.MKSKIPPED[Pair(state.HKr, state.Nr.toInt())] = mk + state.Nr++ + } + } + } + + private fun trySkippedMessageKeys( + state: States, + encHeader: ByteArray, + ciphertext: ByteArray, + ad: ByteArray + ) : ByteArray? { + state.MKSKIPPED.forEach { + val (hk, n) = it.key + val mk = it.value + + val header = hDecrypt(hk, encHeader).run { + Headers.deserialize(this) + } + if(header.n.toInt() == n) { + state.MKSKIPPED.remove(it.key) + return decrypt(mk, ciphertext, concat(ad, encHeader)) + } + } + + return null + } + + private fun decryptHeader( + state: States, + encHeader: ByteArray + ) : Pair { + var header: Headers? = null + try { + header = hDecrypt(state.HKr!!, encHeader).run { + Headers.deserialize(this) + } + } catch(e: Exception) { + e.printStackTrace() + } + + header?.let { + return Pair(header, false) + } + + header = hDecrypt(state.NHKr!!, encHeader).run { + Headers.deserialize(this) + } + + return Pair(header, true) + } + + private fun dhRatchet(state: States, header: Headers) { + state.PN = state.Ns + state.Ns = 0u + state.Nr = 0u + state.HKs = state.NHKs + state.HKr = state.NHKr + state.DHRr = header.dh.public + + kdfRk(state.RK!!, + dh( + state.DHRs!!, + state.DHRr!!, + ) + ).let { + state.RK = it.first + state.CKr = it.second + state.NHKr = it.third + } + + state.DHRs = generateDH() + + kdfRk(state.RK!!, + dh( + state.DHRs!!, + state.DHRr!!, + ) + ).let { + state.RK = it.first + state.CKs = it.second + state.NHKs = it.third + } + } +} \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt new file mode 100644 index 0000000..5d776ba --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -0,0 +1,37 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.util.Pair +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters +import java.security.KeyPair +import java.security.PrivateKey +import java.security.PublicKey + + +data class States( + var RK: ByteArray? = null, + var CKs: ByteArray? = null, + var CKr: ByteArray? = null, + var Ns: UByte = 0u, + var Nr: UByte = 0u, + var PN: UByte = 0u, + var DHRs: AsymmetricCipherKeyPair?, + var DHRr: CipherParameters? = null, + var HKs: ByteArray? = null, + var HKr: ByteArray? = null, + var NHKs: ByteArray? = null, + var NHKr: ByteArray? = null, + var MKSKIPPED: MutableMap, ByteArray> = mutableMapOf() +) { + fun serialize(): String { + return Json.encodeToString(this) + } + + companion object { + fun deserialize(input: String): States { + return Json.decodeFromString(input) + } + } +} \ No newline at end of file diff --git a/double_ratchet/src/main/res/values/strings.xml b/double_ratchet/src/main/res/values/strings.xml new file mode 100644 index 0000000..90a2b76 --- /dev/null +++ b/double_ratchet/src/main/res/values/strings.xml @@ -0,0 +1,9 @@ + + SMSWithoutBorders DoubleRatchet LibSignal + Missing public key + Ratchet states removed + RelaySMS v1 + RelaySMS C2S DR v1 + RelaySMS DRHE v2 + RelaySMS DR_ENCRYPTION v2 + \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..8bdaf60c75ab801e22807dde59e12a8735a34077 GIT binary patch literal 45457 zcma&NW0YlEwk;ePwr$(aux;D69T}N{9ky*d!_2U4+qUuIRNZ#Jck8}7U+vcB{`IjNZqX3eq5;s6ddAkU&5{L|^Ow`ym2B0m+K02+~Q)i807X3X94qi>j)C0e$=H zm31v`=T&y}ACuKx7G~yWSY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DK;pmS{8ZTKs`Js~PYv2|=VkDv{Dtt)cLU@9%K6_KqtqfM zaE*e$f$Xm=;IAURNUXw8g%=?jzG2}10ZA5qXzAaJ@eh)yv5B=ETyVwC-a*CD;GgRJ z4J1~zMUey?4iVlS0zW|F-~0nenLiN3S0)l!T2}D%;<}Z9DzeVgcB+MSj;f$KY;uP%UR#f`0u*@6U@tk@jO3N?Fjq< z{cUUhjrr$rmo>qE?52zKe+>6iP5P_tcUfxsLSy{9*)shB(w`UUveNH`a`kr$VEF@} zKh&|lTD;4;m_H6C&)9#D`kRh;S(NTa=Ve^~xe_0~x$6h8Q@B_qu#ee=(lkI9@F6$0m=z@H=4&h%Q{htM>uHs(Sr@2ry`fgLA zKj8lVXdGPyy)2J%A${}Rm_a{){wHnlM?yGPQ7#KO{8*(_l0QZHuV};nO?c%h?qwSL z3wem|w*2tdxW5&PxC(Wd0QG_w|GPbw|0UFK`u$~U%!`QKcME;=Q@?*erh4_>FP~1n zAldwG9h$$u_$RFK6Uxo20GHqJzc}Rl-EwVz3h4n z;3~%DwD84i>)-8#&#y3k)3BG5cNaP3?t4q}F%yfv?*yEiC>sSo}$f>nh0QNZXH1N)-Q7kbk=2uL9OrF)nXrE@F1y%_8Yn c82=K%QXLKFx%@O{wJjEi6Y56o#$)Bpeg literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2a84e18 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..ef07e01 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega From b0291013bb4cd5ee62355ede7c0dea2bf8a93812 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Sun, 12 Apr 2026 22:18:05 +0100 Subject: [PATCH 06/19] update: Nk looks good - should go to other ones --- .../SecurityAESTest.kt | 9 +- .../SecurityX25519Test.kt | 18 +- .../libsignal/HeadersTest.kt | 17 - .../libsignal/RatchetsTest.kt | 237 ++++--- .../libsignal/StateTest.kt | 3 +- .../libsignal_doubleratchet/CryptoUtils.kt | 77 +++ .../EncryptionController.kt | 647 +++++++++--------- .../SecurityCurve25519.kt | 115 ---- .../extensions/context.kt | 2 + .../libsignal/Protocols.kt | 20 +- .../libsignal/RatchetsHE.kt | 4 +- .../libsignal/States.kt | 2 +- .../src/main/res/values/strings.xml | 1 + 13 files changed, 561 insertions(+), 591 deletions(-) delete mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt delete mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt index ced6619..5b92d58 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt @@ -1,17 +1,20 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet +import android.content.Context +import androidx.test.espresso.internal.inject.InstrumentationContext import androidx.test.filters.SmallTest +import androidx.test.platform.app.InstrumentationRegistry +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.generateRandomBytes import org.junit.Assert.assertArrayEquals import org.junit.Test @SmallTest class SecurityAESTest { - + var context: Context = InstrumentationRegistry.getInstrumentation().targetContext @Test fun aesTest() { val secretKey = SecurityAES.generateSecretKey(256) - - val input = CryptoUtils.generateRandomBytes(277) + val input = context.generateRandomBytes(277) val cipher = SecurityAES.encryptAES256CBC(input, secretKey.encoded, null) val output = SecurityAES.decryptAES256CBC(cipher, secretKey.encoded, null) diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt index b8fa7c2..545634d 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt @@ -1,8 +1,11 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet +import android.content.Context import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import androidx.test.filters.SmallTest +import androidx.test.platform.app.InstrumentationRegistry +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols import org.junit.Assert.assertArrayEquals import org.junit.Test import java.security.KeyPairGenerator @@ -11,6 +14,9 @@ import java.security.Signature @SmallTest class SecurityX25519Test { + + var context: Context = InstrumentationRegistry.getInstrumentation().targetContext + @Test fun keystoreEd25519() { val keystoreAlias = "keystoreAlias" @@ -48,14 +54,12 @@ class SecurityX25519Test { @Test fun sharedSecret() { - val alice = SecurityCurve25519() - val bob = SecurityCurve25519() - - val alicePubKey = alice.generateKey() - val bobPubKey = bob.generateKey() + val protocols = Protocols(context) + val alice = protocols.generateDH() + val bob = protocols.generateDH() - val aliceSharedSecret = alice.calculateSharedSecret(bobPubKey) - val bobSharedSecret = bob.calculateSharedSecret(alicePubKey) + val aliceSharedSecret = protocols.dh(alice, bob.public) + val bobSharedSecret = protocols.dh(bob, alice.public) assertArrayEquals(aliceSharedSecret, bobSharedSecret) } diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt deleted file mode 100644 index 744e6b9..0000000 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/HeadersTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal - -import androidx.test.filters.SmallTest -import junit.framework.TestCase.assertEquals -import org.junit.Test -import java.security.SecureRandom - -@SmallTest -class HeadersTest { - - @Test fun headersTest() { - val header = Headers(SecureRandom.getSeed(32), 0, 0) - val header1 = Headers.deserialize(header.serialized) - - assertEquals(header, header1) - } -} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index 4cd94b0..dc3895b 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -4,9 +4,11 @@ import android.content.Context import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityCurve25519 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.sha256 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.generateRandomBytes +import org.bouncycastle.crypto.params.X25519PublicKeyParameters import org.junit.Assert.assertArrayEquals +import org.junit.Before import org.junit.Test import java.security.SecureRandom @@ -14,146 +16,159 @@ import java.security.SecureRandom class RatchetsTest { var context: Context = InstrumentationRegistry.getInstrumentation().targetContext - @Test - fun completeRatchetHETest() { - val aliceEphemeralKeyPair = SecurityCurve25519() - val aliceEphemeralHeaderKeyPair = SecurityCurve25519() - val aliceEphemeralNextHeaderKeyPair = SecurityCurve25519() - - val bobStaticKeyPair = SecurityCurve25519() - val bobEphemeralKeyPair = SecurityCurve25519() - val bobEphemeralHeaderKeyPair = SecurityCurve25519() - val bobEphemeralNextHeaderKeyPair = SecurityCurve25519() - - val aliceNonce = CryptoUtils.generateRandomBytes(16) - val bobNonce = CryptoUtils.generateRandomBytes(16) - - val (aliceSk, aliceSkH, aliceSkNh) = SecurityCurve25519(aliceEphemeralKeyPair.privateKey) - .agreeWithAuthAndNonce( - authenticationPublicKey = bobStaticKeyPair.generateKey(), - authenticationPrivateKey = null, - headerPrivateKey = aliceEphemeralHeaderKeyPair.privateKey, - nextHeaderPrivateKey = aliceEphemeralNextHeaderKeyPair.privateKey, - publicKey = bobEphemeralKeyPair.generateKey(), - headerPublicKey = bobEphemeralHeaderKeyPair.generateKey(), - nextHeaderPublicKey = bobEphemeralNextHeaderKeyPair.generateKey(), - salt = context.getString(R.string.dr_salt).encodeToByteArray(), - nonce1 = aliceNonce, - nonce2 = bobNonce, - info = context.getString(R.string.dr_info).encodeToByteArray() - ) + val protocol = Protocols(context) + + lateinit var aliceRk: ByteArray + lateinit var aliceHk: ByteArray + lateinit var aliceNhk: ByteArray + + lateinit var bobRk: ByteArray + lateinit var bobHk: ByteArray + lateinit var bobNhk: ByteArray + + val aliceKeypair = protocol.generateDH() + val bobStaticKeypair = protocol.generateDH() + val bobKeypair = protocol.generateDH() + + val salt = "completeRatchetTest_v1".encodeToByteArray() + val info = context.generateRandomBytes(16) + + (aliceKeypair.public as X25519PublicKeyParameters).encoded + + (bobKeypair.public as X25519PublicKeyParameters).encoded + + (bobStaticKeypair.public as X25519PublicKeyParameters).encoded + + @Before + fun start() { + CryptoUtils.generateKeysNK( + context = context, + ephemeralKeyPair = aliceKeypair, + authenticationPublicKey = bobStaticKeypair.public, + ephemeralPublicKey = bobKeypair.public, + salt = salt, + info = info + ).let { + aliceRk = it.first + aliceHk = it.second + aliceNhk = it.third + } - val (bobSk, bobSkH, bobSkNh) = SecurityCurve25519(bobEphemeralKeyPair.privateKey) - .agreeWithAuthAndNonce( - authenticationPublicKey = null, - authenticationPrivateKey = bobStaticKeyPair.privateKey, - headerPrivateKey = bobEphemeralHeaderKeyPair.privateKey, - nextHeaderPrivateKey = bobEphemeralNextHeaderKeyPair.privateKey, - publicKey = aliceEphemeralKeyPair.generateKey(), - headerPublicKey = aliceEphemeralHeaderKeyPair.generateKey(), - nextHeaderPublicKey = aliceEphemeralNextHeaderKeyPair.generateKey(), - salt = context.getString(R.string.dr_salt).encodeToByteArray(), - nonce1 = aliceNonce, - nonce2 = bobNonce, - info = context.getString(R.string.dr_info).encodeToByteArray() - ) + CryptoUtils.generateKeysNKServer( + context = context, + authenticationKeypair = bobStaticKeypair, + ephemeralKeyPair = bobKeypair, + ephemeralPublicKey = aliceKeypair.public, + salt = salt, + info = info + ).let { + bobRk = it.first + bobHk = it.second + bobNhk = it.third + } - assertArrayEquals(aliceSk, bobSk) - assertArrayEquals(aliceSkH, bobSkH) - assertArrayEquals(aliceSkNh, bobSkNh) + assertArrayEquals(aliceRk, bobRk) + assertArrayEquals(aliceHk, bobHk) + assertArrayEquals(aliceNhk, bobNhk) + } + @Test + fun completeRatchetTest() { + val ratchets = RatchetsHE(context) val aliceState = States() - RatchetsHE.ratchetInitAlice( + ratchets.ratchetInitAlice( state = aliceState, - SK = aliceSk, - bobDhPublicKey = bobEphemeralKeyPair.generateKey(), - sharedHka = aliceSkH, - sharedNhkb = aliceSkNh + sk = aliceRk, + bobDhPublicKey = bobKeypair.public, + sharedHka = aliceHk, + sharedNHka = aliceNhk ) val bobState = States() - RatchetsHE.ratchetInitBob( + ratchets.ratchetInitBob( state = bobState, - SK = bobSk, - bobDhPublicKeypair = bobEphemeralKeyPair.getKeypair(), - sharedHka = bobSkH, - sharedNhkb = bobSkNh + sk = bobRk, + bobKeypair = bobKeypair, + sharedHka = bobHk, + sharedNHka = bobNhk ) val originalText = SecureRandom.getSeed(32); - val (encHeader, aliceCipherText) = RatchetsHE.ratchetEncrypt( - aliceState, - originalText, - bobStaticKeyPair.generateKey() - ) - var encHeader1: ByteArray? = null - var aliceCipherText1: ByteArray? = null - for(i in 1..10) { - val (encHeader2, aliceCipherText2) = RatchetsHE.ratchetEncrypt( - aliceState, - originalText, - bobStaticKeyPair.generateKey() - ) - encHeader1 = encHeader2 - aliceCipherText1 = aliceCipherText2 - } + val ad = "RatchetsTest".encodeToByteArray().sha256() + var ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) - val bobPlainText = RatchetsHE.ratchetDecrypt( + var plaintext = ratchets.ratchetDecrypt( state = bobState, - encHeader = encHeader, - cipherText = aliceCipherText, - AD = bobStaticKeyPair.generateKey() + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad ) - val bobPlainText1 = RatchetsHE.ratchetDecrypt( + assertArrayEquals(originalText, plaintext) + + ratchetPayload = ratchets.ratchetEncrypt( state = bobState, - encHeader = encHeader1!!, - cipherText = aliceCipherText1!!, - AD = bobStaticKeyPair.generateKey() + plaintext = originalText, + ad = ad ) - assertArrayEquals(originalText, bobPlainText) - assertArrayEquals(originalText, bobPlainText1) + plaintext = ratchets.ratchetDecrypt( + state = aliceState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) } @Test - fun completeRatchetTest() { - val alice = SecurityCurve25519() - val bob = SecurityCurve25519() - - val SK = alice.calculateSharedSecret(bob.generateKey()) - val SK1 = bob.calculateSharedSecret(alice.generateKey()) - assertArrayEquals(SK, SK1) - + fun completeRatchetOutOfOrderTest() { + val ratchets = RatchetsHE(context) val aliceState = States() - Ratchets.ratchetInitAlice(aliceState, SK, bob.generateKey()) + ratchets.ratchetInitAlice( + state = aliceState, + sk = aliceRk, + bobDhPublicKey = bobKeypair.public, + sharedHka = aliceHk, + sharedNHka = aliceNhk + ) val bobState = States() - Ratchets.ratchetInitBob(bobState, SK, bob.getKeypair()) + ratchets.ratchetInitBob( + state = bobState, + sk = bobRk, + bobKeypair = bobKeypair, + sharedHka = bobHk, + sharedNHka = bobNhk + ) val originalText = SecureRandom.getSeed(32); - val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, - bob.generateKey()) - - var header1: Headers? = null - var aliceCipherText1: ByteArray? = null - for(i in 1..10) { - val (header, aliceCipherText) = Ratchets.ratchetEncrypt(aliceState, originalText, - bob.generateKey()) - header1 = header - aliceCipherText1 = aliceCipherText - } - val bobPlainText = Ratchets.ratchetDecrypt(bobState, header, aliceCipherText, - bob.generateKey()) + val ad = "RatchetsTest".encodeToByteArray().sha256() + var ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + for(i in 1..5) { + ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + } - val bobPlainText1 = Ratchets.ratchetDecrypt(bobState, header1, aliceCipherText1, - bob.generateKey()) - println(bobState.serialize()) + val plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) - assertArrayEquals(originalText, bobPlainText) - assertArrayEquals(originalText, bobPlainText1) + assertArrayEquals(originalText, plaintext) } } diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt index 42c254e..addb3f4 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/StateTest.kt @@ -1,5 +1,6 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal +import android.util.Pair import androidx.test.filters.SmallTest import junit.framework.TestCase.assertEquals import kotlinx.serialization.json.Json @@ -11,8 +12,6 @@ class StateTest { @Test fun testStates() { val state = States() - state.DHs = android.util.Pair(SecureRandom.getSeed(32), - SecureRandom.getSeed(32)) val serializedStates = Json.encodeToString(state) val deserializedStates = Json.decodeFromString(serializedStates) assertEquals(state, deserializedStates) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt index 8060e1d..f73ea4c 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -1,8 +1,13 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet +import android.content.Context import at.favre.lib.hkdf.HKDF +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols import com.google.common.primitives.Bytes +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters import java.security.GeneralSecurityException +import java.security.MessageDigest import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.SecretKey @@ -32,4 +37,76 @@ object CryptoUtils { return output } + fun generateKeysNK( + context: Context, + ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationPublicKey: CipherParameters, + ephemeralPublicKey: CipherParameters, + salt: ByteArray, + info: ByteArray, + ): Triple { + val protocols = Protocols(context) + val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + return hkdf( + ikm = dh1, + salt = salt, + info = info, + len = 32, + ).run { + hkdf( + ikm = dh2, + salt = this, + info = info, + len = 96, + ).run { + Triple( + this.sliceArray(0 until 32), + this.sliceArray(32 until 64), + this.sliceArray(64 until 96), + ) + } + } + } + + fun generateKeysNKServer( + context: Context, + authenticationKeypair: AsymmetricCipherKeyPair, + ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralPublicKey: CipherParameters, + salt: ByteArray, + info: ByteArray, + ): Triple { + val protocols = Protocols(context) + val dh1 = protocols.dh(authenticationKeypair, ephemeralPublicKey) + val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + return hkdf( + ikm = dh1, + salt = salt, + info = info, + len = 32, + ).run { + hkdf( + ikm = dh2, + salt = this, + info = info, + len = 96, + ).run { + Triple( + this.sliceArray(0 until 32), + this.sliceArray(32 until 64), + this.sliceArray(64 until 96), + ) + } + } + } + + fun ByteArray.sha256(): ByteArray { + return MessageDigest + .getInstance("SHA-256") + .digest(this) + } + + + } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt index a72bed4..26e3f7a 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt @@ -11,7 +11,6 @@ import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getKeyp import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.saveBinaryDataEncrypted import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.setKeypairValues import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Headers -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Ratchets import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.States import com.google.gson.Gson import kotlinx.coroutines.CoroutineScope @@ -23,326 +22,326 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable -object EncryptionController { - - @Serializable - enum class SecureRequestMode { - REQUEST_NONE, - REQUEST_REQUESTED, - REQUEST_RECEIVED, - REQUEST_ACCEPTED, - } - - enum class MessageRequestType(val code: Byte) { - TYPE_REQUEST(0x01.toByte()), - TYPE_ACCEPT(0x02.toByte()), - TYPE_MESSAGE(0x03.toByte()); - - companion object { - fun fromCode(code: Byte): MessageRequestType? = - entries.find { it.code == code } // Kotlin 1.9+, use values() before that - - fun fromMessage(message: ByteArray): MessageRequestType? = - entries.find { it.code == message[0] } // Kotlin 1.9+, use values() before that - } - } - - private fun extractRequestPublicKey( publicKey: ByteArray) : ByteArray { - val lenPubKey = publicKey[1].toInt() - return publicKey.drop(2).toByteArray() - } - - private fun extractMessage(data: ByteArray) : Pair { - val lenHeader = data[1].toInt() - val lenMessage = data[2].toInt() - val header = data.copyOfRange(3, 3 + lenHeader) - val message = data.copyOfRange(3 + lenHeader, (3 + lenHeader + lenMessage)) - return Pair(Headers.deserialize(header), message) - } - - @OptIn(ExperimentalUnsignedTypes::class) - private fun formatRequestPublicKey( - publicKey: ByteArray, - type: MessageRequestType - ) : ByteArray { - val mn = ubyteArrayOf(type.code.toUByte()) - val lenPubKey = ubyteArrayOf(publicKey.size.toUByte()) - - return (mn + lenPubKey).toByteArray() + publicKey - } - - @OptIn(ExperimentalUnsignedTypes::class) - private fun formatMessage( - header: Headers, - cipherText: ByteArray - ) : ByteArray { - val mn = ubyteArrayOf(MessageRequestType.TYPE_MESSAGE.code.toUByte()) - val lenHeader = ubyteArrayOf(header.serialized.size.toUByte()) - val lenMessage = ubyteArrayOf(cipherText.size.toUByte()) - - return (mn + lenHeader + lenMessage).toByteArray() + header.serialized + cipherText - } - - suspend fun sendRequest( - context: Context, - address: String, - mode: SecureRequestMode, - ): ByteArray { - try { - val publicKey = generateIdentityPublicKeys(context, address) - - var type: MessageRequestType? = null - val mode = when(mode) { - SecureRequestMode.REQUEST_RECEIVED -> { - type = MessageRequestType.TYPE_ACCEPT - SecureRequestMode.REQUEST_ACCEPTED - } - else -> { - type = MessageRequestType.TYPE_REQUEST - SecureRequestMode.REQUEST_REQUESTED - } - } - - context.setEncryptionModeStates(address, mode) - return formatRequestPublicKey(publicKey, type) - } catch (e: Exception) { - throw e - } - } - - suspend fun receiveRequest( - context: Context, - address: String, - publicKey: ByteArray, - ) : ByteArray? { - MessageRequestType.fromCode(publicKey[0])?.let { type -> - val publicKey = extractRequestPublicKey(publicKey) - try { - val mode = when(type) { - MessageRequestType.TYPE_REQUEST -> { - SecureRequestMode.REQUEST_RECEIVED - } - MessageRequestType.TYPE_ACCEPT -> { - context.removeEncryptionRatchetStates(address) - SecureRequestMode.REQUEST_ACCEPTED - } - else -> return null - } - context.setEncryptionModeStates( - address, - mode, - publicKey, - ) - } catch (e: Exception) { - throw e - } - return publicKey - } - - return null - } - - @Throws - private suspend fun generateIdentityPublicKeys( - context: Context, - address: String - ): ByteArray { - try { - val libSigCurve25519 = SecurityCurve25519() - val publicKey = libSigCurve25519.generateKey() - context.setKeypairValues(address, publicKey, libSigCurve25519.privateKey) - return publicKey - } catch (e: Exception) { - throw e - } - } - - @Throws - suspend fun decrypt( - context: Context, - address: String, - text: String - ): String? { - - val data = Base64.decode(text, Base64.DEFAULT) - if(MessageRequestType.fromCode(data[0]) != MessageRequestType.TYPE_MESSAGE) - return null - - val payload = try { extractMessage(data) } catch(e: Exception) { - throw e - } - - val modeStates = context.getEncryptionModeStatesSync(address) - val publicKey = Gson().fromJson(modeStates, - SavedEncryptedModes::class.java).publicKey - - if(publicKey == null) { - CoroutineScope(Dispatchers.Main).launch { - Toast.makeText( - context, - context.getString(R.string.missing_public_key), - Toast.LENGTH_LONG).show() - } - return null - } - - val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) - - val keystore = address + "_ratchet_state" - val currentState = context.getEncryptedBinaryData(keystore) - - var state: States? - if(currentState == null) { - state = States() - val sk = context.calculateSharedSecret(address, publicKeyBytes) - val keypair = context.getKeypairValues(address) //public private - - Ratchets.ratchetInitBob( - state, - sk, - android.util.Pair(keypair.second, keypair.first) - ) - } - else state = States.deserialize(String(currentState)) - - val keypair = context.getKeypairValues(address) - var decryptedText: String? - try { - decryptedText = String(Ratchets.ratchetDecrypt( - state, - payload.first, - payload.second, - keypair.first - )) - context.saveBinaryDataEncrypted(keystore, - state.serialize().encodeToByteArray()) - } catch(e: Exception) { - throw e - } - return decryptedText - } - - @Throws - suspend fun encrypt( - context: Context, - address: String, - text: String - ) : String? { - val modeStates = context.getEncryptionModeStatesSync(address) - val publicKey = Gson().fromJson(modeStates, - SavedEncryptedModes::class.java).publicKey - - if(publicKey == null) { - CoroutineScope(Dispatchers.Main).launch { - Toast.makeText( - context, - context.getString(R.string.missing_public_key), - Toast.LENGTH_LONG).show() - } - return null - } - - val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) - - val keystore = address + "_ratchet_state" - val currentState = context.getEncryptedBinaryData(keystore) - - var state: States? - if(currentState == null) { - state = States() - val sk = context.calculateSharedSecret(address, publicKeyBytes) - Ratchets.ratchetInitAlice(state, sk, publicKeyBytes) - } - else state = States.deserialize(String(currentState)) - - val ratchetOutput = Ratchets.ratchetEncrypt(state, - text.encodeToByteArray(), publicKeyBytes) - - return try { - val message = formatMessage( - ratchetOutput.first, - ratchetOutput.second - ) - context.saveBinaryDataEncrypted(keystore, - state.serialize().encodeToByteArray()) - Base64.encodeToString(message, Base64.DEFAULT) - } catch(e: Exception) { - throw e - } - } -} - -private suspend fun Context.calculateSharedSecret( - address: String, - publicKey: ByteArray -): ByteArray? { - val keypair = getKeypairValues(address) //public private - keypair.second?.let { privateKey -> - val libSigCurve25519 = SecurityCurve25519(privateKey) - return libSigCurve25519.calculateSharedSecret(publicKey) - } - return null -} - -data class SavedEncryptedModes( - var mode: EncryptionController.SecureRequestMode, - var publicKey: String? = null, -) - -private suspend fun Context.setEncryptionModeStates( - address: String, - mode: EncryptionController.SecureRequestMode, - publicKey: ByteArray? = null, -) { - val keyValue = stringPreferencesKey(address + "_mode_states") - dataStore.edit { secureComms -> - // Make a mutable copy of existing state - val currentState = secureComms[keyValue] ?: "" - val savedEncryptedModes = if(currentState.isNotEmpty()) Gson() - .fromJson(currentState, SavedEncryptedModes::class.java) - .apply { this.mode = mode } - else SavedEncryptedModes(mode = mode) - - publicKey?.let { publicKey -> - savedEncryptedModes.publicKey = - Base64.encodeToString(publicKey, Base64.DEFAULT) - } - - secureComms[keyValue] = Gson().toJson(savedEncryptedModes) - } -} - -suspend fun Context.removeEncryptionRatchetStates(address: String) { - val keyValue = stringPreferencesKey(address + "_ratchet_state") - dataStore.edit { secureComms -> - secureComms.remove(keyValue) - withContext(Dispatchers.Main) { - Toast.makeText( - this@removeEncryptionRatchetStates, - getString(R.string.ratchet_states_removed), - Toast.LENGTH_LONG).show() - } - } -} - -suspend fun Context.removeEncryptionModeStates(address: String) { - val keyValue = stringPreferencesKey(address + "_mode_states") - dataStore.edit { secureComms -> - secureComms.remove(keyValue) - } -} - -fun Context.getEncryptionRatchetStates(address: String): Flow { - val keyValue = stringPreferencesKey(address + "_ratchet_state") - return dataStore.data.map { it[keyValue] } -} - -suspend fun Context.getEncryptionModeStatesSync(address: String): String? { - val keyValue = stringPreferencesKey(address + "_mode_states") - return dataStore.data.first()[keyValue] -} - -fun Context.getEncryptionModeStates(address: String): Flow { - val keyValue = stringPreferencesKey(address + "_mode_states") - return dataStore.data.map { it[keyValue] } -} +//object EncryptionController { +// +// @Serializable +// enum class SecureRequestMode { +// REQUEST_NONE, +// REQUEST_REQUESTED, +// REQUEST_RECEIVED, +// REQUEST_ACCEPTED, +// } +// +// enum class MessageRequestType(val code: Byte) { +// TYPE_REQUEST(0x01.toByte()), +// TYPE_ACCEPT(0x02.toByte()), +// TYPE_MESSAGE(0x03.toByte()); +// +// companion object { +// fun fromCode(code: Byte): MessageRequestType? = +// entries.find { it.code == code } // Kotlin 1.9+, use values() before that +// +// fun fromMessage(message: ByteArray): MessageRequestType? = +// entries.find { it.code == message[0] } // Kotlin 1.9+, use values() before that +// } +// } +// +// private fun extractRequestPublicKey( publicKey: ByteArray) : ByteArray { +// val lenPubKey = publicKey[1].toInt() +// return publicKey.drop(2).toByteArray() +// } +// +// private fun extractMessage(data: ByteArray) : Pair { +// val lenHeader = data[1].toInt() +// val lenMessage = data[2].toInt() +// val header = data.copyOfRange(3, 3 + lenHeader) +// val message = data.copyOfRange(3 + lenHeader, (3 + lenHeader + lenMessage)) +// return Pair(Headers.deserialize(header), message) +// } +// +// @OptIn(ExperimentalUnsignedTypes::class) +// private fun formatRequestPublicKey( +// publicKey: ByteArray, +// type: MessageRequestType +// ) : ByteArray { +// val mn = ubyteArrayOf(type.code.toUByte()) +// val lenPubKey = ubyteArrayOf(publicKey.size.toUByte()) +// +// return (mn + lenPubKey).toByteArray() + publicKey +// } +// +// @OptIn(ExperimentalUnsignedTypes::class) +// private fun formatMessage( +// header: Headers, +// cipherText: ByteArray +// ) : ByteArray { +// val mn = ubyteArrayOf(MessageRequestType.TYPE_MESSAGE.code.toUByte()) +// val lenHeader = ubyteArrayOf(header.serialized.size.toUByte()) +// val lenMessage = ubyteArrayOf(cipherText.size.toUByte()) +// +// return (mn + lenHeader + lenMessage).toByteArray() + header.serialized + cipherText +// } +// +// suspend fun sendRequest( +// context: Context, +// address: String, +// mode: SecureRequestMode, +// ): ByteArray { +// try { +// val publicKey = generateIdentityPublicKeys(context, address) +// +// var type: MessageRequestType? = null +// val mode = when(mode) { +// SecureRequestMode.REQUEST_RECEIVED -> { +// type = MessageRequestType.TYPE_ACCEPT +// SecureRequestMode.REQUEST_ACCEPTED +// } +// else -> { +// type = MessageRequestType.TYPE_REQUEST +// SecureRequestMode.REQUEST_REQUESTED +// } +// } +// +// context.setEncryptionModeStates(address, mode) +// return formatRequestPublicKey(publicKey, type) +// } catch (e: Exception) { +// throw e +// } +// } +// +// suspend fun receiveRequest( +// context: Context, +// address: String, +// publicKey: ByteArray, +// ) : ByteArray? { +// MessageRequestType.fromCode(publicKey[0])?.let { type -> +// val publicKey = extractRequestPublicKey(publicKey) +// try { +// val mode = when(type) { +// MessageRequestType.TYPE_REQUEST -> { +// SecureRequestMode.REQUEST_RECEIVED +// } +// MessageRequestType.TYPE_ACCEPT -> { +// context.removeEncryptionRatchetStates(address) +// SecureRequestMode.REQUEST_ACCEPTED +// } +// else -> return null +// } +// context.setEncryptionModeStates( +// address, +// mode, +// publicKey, +// ) +// } catch (e: Exception) { +// throw e +// } +// return publicKey +// } +// +// return null +// } +// +// @Throws +// private suspend fun generateIdentityPublicKeys( +// context: Context, +// address: String +// ): ByteArray { +// try { +// val libSigCurve25519 = SecurityCurve25519() +// val publicKey = libSigCurve25519.generateKey() +// context.setKeypairValues(address, publicKey, libSigCurve25519.privateKey) +// return publicKey +// } catch (e: Exception) { +// throw e +// } +// } +// +// @Throws +// suspend fun decrypt( +// context: Context, +// address: String, +// text: String +// ): String? { +// +// val data = Base64.decode(text, Base64.DEFAULT) +// if(MessageRequestType.fromCode(data[0]) != MessageRequestType.TYPE_MESSAGE) +// return null +// +// val payload = try { extractMessage(data) } catch(e: Exception) { +// throw e +// } +// +// val modeStates = context.getEncryptionModeStatesSync(address) +// val publicKey = Gson().fromJson(modeStates, +// SavedEncryptedModes::class.java).publicKey +// +// if(publicKey == null) { +// CoroutineScope(Dispatchers.Main).launch { +// Toast.makeText( +// context, +// context.getString(R.string.missing_public_key), +// Toast.LENGTH_LONG).show() +// } +// return null +// } +// +// val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) +// +// val keystore = address + "_ratchet_state" +// val currentState = context.getEncryptedBinaryData(keystore) +// +// var state: States? +// if(currentState == null) { +// state = States() +// val sk = context.calculateSharedSecret(address, publicKeyBytes) +// val keypair = context.getKeypairValues(address) //public private +// +// Ratchets.ratchetInitBob( +// state, +// sk, +// android.util.Pair(keypair.second, keypair.first) +// ) +// } +// else state = States.deserialize(String(currentState)) +// +// val keypair = context.getKeypairValues(address) +// var decryptedText: String? +// try { +// decryptedText = String(Ratchets.ratchetDecrypt( +// state, +// payload.first, +// payload.second, +// keypair.first +// )) +// context.saveBinaryDataEncrypted(keystore, +// state.serialize().encodeToByteArray()) +// } catch(e: Exception) { +// throw e +// } +// return decryptedText +// } +// +// @Throws +// suspend fun encrypt( +// context: Context, +// address: String, +// text: String +// ) : String? { +// val modeStates = context.getEncryptionModeStatesSync(address) +// val publicKey = Gson().fromJson(modeStates, +// SavedEncryptedModes::class.java).publicKey +// +// if(publicKey == null) { +// CoroutineScope(Dispatchers.Main).launch { +// Toast.makeText( +// context, +// context.getString(R.string.missing_public_key), +// Toast.LENGTH_LONG).show() +// } +// return null +// } +// +// val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) +// +// val keystore = address + "_ratchet_state" +// val currentState = context.getEncryptedBinaryData(keystore) +// +// var state: States? +// if(currentState == null) { +// state = States() +// val sk = context.calculateSharedSecret(address, publicKeyBytes) +// Ratchets.ratchetInitAlice(state, sk, publicKeyBytes) +// } +// else state = States.deserialize(String(currentState)) +// +// val ratchetOutput = Ratchets.ratchetEncrypt(state, +// text.encodeToByteArray(), publicKeyBytes) +// +// return try { +// val message = formatMessage( +// ratchetOutput.first, +// ratchetOutput.second +// ) +// context.saveBinaryDataEncrypted(keystore, +// state.serialize().encodeToByteArray()) +// Base64.encodeToString(message, Base64.DEFAULT) +// } catch(e: Exception) { +// throw e +// } +// } +//} +// +//private suspend fun Context.calculateSharedSecret( +// address: String, +// publicKey: ByteArray +//): ByteArray? { +// val keypair = getKeypairValues(address) //public private +// keypair.second?.let { privateKey -> +// val libSigCurve25519 = SecurityCurve25519(privateKey) +// return libSigCurve25519.calculateSharedSecret(publicKey) +// } +// return null +//} +// +//data class SavedEncryptedModes( +// var mode: EncryptionController.SecureRequestMode, +// var publicKey: String? = null, +//) +// +//private suspend fun Context.setEncryptionModeStates( +// address: String, +// mode: EncryptionController.SecureRequestMode, +// publicKey: ByteArray? = null, +//) { +// val keyValue = stringPreferencesKey(address + "_mode_states") +// dataStore.edit { secureComms -> +// // Make a mutable copy of existing state +// val currentState = secureComms[keyValue] ?: "" +// val savedEncryptedModes = if(currentState.isNotEmpty()) Gson() +// .fromJson(currentState, SavedEncryptedModes::class.java) +// .apply { this.mode = mode } +// else SavedEncryptedModes(mode = mode) +// +// publicKey?.let { publicKey -> +// savedEncryptedModes.publicKey = +// Base64.encodeToString(publicKey, Base64.DEFAULT) +// } +// +// secureComms[keyValue] = Gson().toJson(savedEncryptedModes) +// } +//} +// +//suspend fun Context.removeEncryptionRatchetStates(address: String) { +// val keyValue = stringPreferencesKey(address + "_ratchet_state") +// dataStore.edit { secureComms -> +// secureComms.remove(keyValue) +// withContext(Dispatchers.Main) { +// Toast.makeText( +// this@removeEncryptionRatchetStates, +// getString(R.string.ratchet_states_removed), +// Toast.LENGTH_LONG).show() +// } +// } +//} +// +//suspend fun Context.removeEncryptionModeStates(address: String) { +// val keyValue = stringPreferencesKey(address + "_mode_states") +// dataStore.edit { secureComms -> +// secureComms.remove(keyValue) +// } +//} +// +//fun Context.getEncryptionRatchetStates(address: String): Flow { +// val keyValue = stringPreferencesKey(address + "_ratchet_state") +// return dataStore.data.map { it[keyValue] } +//} +// +//suspend fun Context.getEncryptionModeStatesSync(address: String): String? { +// val keyValue = stringPreferencesKey(address + "_mode_states") +// return dataStore.data.first()[keyValue] +//} +// +//fun Context.getEncryptionModeStates(address: String): Flow { +// val keyValue = stringPreferencesKey(address + "_mode_states") +// return dataStore.data.map { it[keyValue] } +//} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt deleted file mode 100644 index 9f3bc28..0000000 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityCurve25519.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.content.Context -import android.util.Pair -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols -import org.bouncycastle.crypto.AsymmetricCipherKeyPair -import org.bouncycastle.crypto.CipherParameters -import org.bouncycastle.crypto.EphemeralKeyPair -import org.bouncycastle.math.ec.custom.djb.Curve25519 - - -class SecurityCurve25519(context: Context) : Protocols(context) { - - private fun generateKey( - ephemeralKeyPair: AsymmetricCipherKeyPair, - authenticationPublicKey: CipherParameters, - ephemeralPublicKey: CipherParameters, - salt: ByteArray, - info: ByteArray, - handshakeSalt: ByteArray, - ) { - val dh1 = dh(ephemeralKeyPair, authenticationPublicKey) - val dh2 = dh(ephemeralKeyPair, ephemeralPublicKey) - return CryptoUtils.hkdf( - handshakeSalt, - salt, - info, - 32, - ).run { - CryptoUtils.hkdf( - dh1, - this, - info, - 32, - ).run { - CryptoUtils.hkdf( - dh2, - this, - info, - 32, - ) - } - } - } - - fun agreeWithAuthAndNonce( - e: AsymmetricCipherKeyPair, - s: CipherParameters, - he: CipherParameters, - hne: CipherParameters, - salt: ByteArray, - nonce1: ByteArray, - nonce2: ByteArray, - info: ByteArray, - hInfo: ByteArray, - ): Triple { - val handshakeSalt = nonce1 + nonce2 - val rootKey = generateKey( - ephemeralKeyPair = ephemeralKeyPair, - authenticationPublicKey = authenticationPublicKey, - publicKey = TODO(), - salt = TODO(), - info = TODO(), - handshakeSalt = TODO() - ) - - val headerKey = agreeWithAuthAndNonceImpl( - authenticationPublicKey = authenticationPublicKey, - authenticationPrivateKey = authenticationPrivateKey, - publicKey = headerPublicKey, - salt = salt, - info = headerInfo, - handshakeSalt = handshakeSalt, - privateKey = headerPrivateKey - ) - - val nextHeaderKey = agreeWithAuthAndNonceImpl( - authenticationPublicKey = authenticationPublicKey, - authenticationPrivateKey = authenticationPrivateKey, - publicKey = nextHeaderPublicKey, - salt = salt, - info = headerInfo, - handshakeSalt = handshakeSalt, - privateKey = nextHeaderPrivateKey - ) - - return Triple(rootKey, headerKey, nextHeaderKey) - } - - fun calculateSharedSecret( - publicKey: ByteArray, - ): ByteArray { - return Curve25519.sharedSecret(this.privateKey, publicKey) - } - - fun calculateSharedSecret( - publicKey: ByteArray, - salt: ByteArray? = null, - info: ByteArray? = "x25591_key_exchange".encodeToByteArray(), - ): ByteArray { - val sharedKey = Curve25519.sharedSecret(this.privateKey, publicKey) - return CryptoUtils.hkdf( - "HMACSHA256", - sharedKey, - salt, - info, - 32, - 1 - )[0] - } - - fun getKeypair(): Pair { - return Pair(privateKey, generateKey()) - } -} \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt index d970fd9..9cafd07 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt @@ -16,6 +16,7 @@ import java.io.IOException import java.security.KeyPair import java.security.KeyStore import java.security.KeyStoreException +import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.security.UnrecoverableEntryException @@ -152,3 +153,4 @@ fun Context.generateRandomBytes(length: Int): ByteArray { random.nextBytes(bytes) return bytes } + diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index ff7ad07..8ff979d 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -30,6 +30,8 @@ import java.security.Security */ open class Protocols(private val context: Context) { + private val MAC_LEN = 64 + init { Security.removeProvider("BC") Security.addProvider(BouncyCastleProvider()) @@ -127,19 +129,19 @@ open class Protocols(private val context: Context) { len = len, ).run { val authKey = this.sliceArray(32 until 64) - val cipherText = cipherText.dropLast(32).toByteArray() + val plaintextCiphertext = cipherText.dropLast(MAC_LEN).toByteArray() val mac = hmac(authKey) - mac.update(ad + cipherText) + mac.update(ad + plaintextCiphertext) - val incomingMac = cipherText.takeLast(32).toByteArray() + val incomingMac = cipherText.takeLast(MAC_LEN).toByteArray() if(!incomingMac.contentEquals(mac.doFinal())) { throw Exception("Message failed authentication") } val key = this.sliceArray(0 until 32) val iv = this.sliceArray(64 until 80) - SecurityAES.decryptAES256CBC(cipherText, key, iv) + SecurityAES.decryptAES256CBC(plaintextCiphertext, key, iv) } } @@ -152,19 +154,19 @@ open class Protocols(private val context: Context) { len = len, ).run { val authKey = this.sliceArray(32 until 64) - val cipherText = cipherText.dropLast(32).toByteArray() - val mac = hmac(authKey) - mac.update(cipherText) - val incomingMac = cipherText.takeLast(32).toByteArray() + val plainCiphertext = cipherText.dropLast(MAC_LEN).toByteArray() + mac.update(plainCiphertext) + + val incomingMac = cipherText.takeLast(MAC_LEN).toByteArray() if(!incomingMac.contentEquals(mac.doFinal())) { throw Exception("Message failed authentication") } val key = this.sliceArray(0 until 32) val iv = this.sliceArray(64 until 80) - SecurityAES.decryptAES256CBC(cipherText, key, iv) + SecurityAES.decryptAES256CBC(plainCiphertext, key, iv) } } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index eb30786..8bcf04d 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -55,11 +55,11 @@ class RatchetsHE(context: Context) : Protocols(context){ fun ratchetInitBob( state: States, sk: ByteArray, - bobDhPublicKeypair: AsymmetricCipherKeyPair, + bobKeypair: AsymmetricCipherKeyPair, sharedHka: ByteArray, sharedNHka: ByteArray, ) { - state.DHRs = bobDhPublicKeypair + state.DHRs = bobKeypair state.DHRr = null state.RK = sk state.CKs = null diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt index 5d776ba..fe0b438 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -17,7 +17,7 @@ data class States( var Ns: UByte = 0u, var Nr: UByte = 0u, var PN: UByte = 0u, - var DHRs: AsymmetricCipherKeyPair?, + var DHRs: AsymmetricCipherKeyPair? = null, var DHRr: CipherParameters? = null, var HKs: ByteArray? = null, var HKr: ByteArray? = null, diff --git a/double_ratchet/src/main/res/values/strings.xml b/double_ratchet/src/main/res/values/strings.xml index 90a2b76..cfccd9c 100644 --- a/double_ratchet/src/main/res/values/strings.xml +++ b/double_ratchet/src/main/res/values/strings.xml @@ -6,4 +6,5 @@ RelaySMS C2S DR v1 RelaySMS DRHE v2 RelaySMS DR_ENCRYPTION v2 + RelaySMS_NK_handshake_v1 \ No newline at end of file From 996e088dacba1d106cdbfeb9019fe1b05eaba820 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Sun, 12 Apr 2026 22:27:09 +0100 Subject: [PATCH 07/19] update: Nk looks good - should go to other ones --- .../libsignal/RatchetsTest.kt | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index dc3895b..e4a60aa 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -161,8 +161,23 @@ class RatchetsTest { ) } - val plaintext = ratchets.ratchetDecrypt( + var plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + + ratchetPayload = ratchets.ratchetEncrypt( state = bobState, + plaintext = originalText, + ad = ad + ) + + plaintext = ratchets.ratchetDecrypt( + state = aliceState, encHeader = ratchetPayload.header, cipherText = ratchetPayload.cipherText, ad = ad From c707cbcfceff29f92101bb05199cb93512b76e1a Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 12:17:32 +0100 Subject: [PATCH 08/19] update: integrated the IK keys for forward secrecy --- .../libsignal_doubleratchet/CryptoUtils.kt | 140 +++++++ .../libsignal_doubleratchet/Cryptography.kt | 77 ++++ .../EncryptionController.kt | 347 ------------------ 3 files changed, 217 insertions(+), 347 deletions(-) create mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt delete mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt index f73ea4c..6f8b648 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -6,8 +6,11 @@ import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocol import com.google.common.primitives.Bytes import org.bouncycastle.crypto.AsymmetricCipherKeyPair import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.EphemeralKeyPair +import org.bouncycastle.crypto.params.X25519PublicKeyParameters import java.security.GeneralSecurityException import java.security.MessageDigest +import java.security.PublicKey import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.SecretKey @@ -101,6 +104,143 @@ object CryptoUtils { } } + data class NoiseIKKey( + val keys: Triple, + val h: ByteArray + ) + + fun generateKeysIK( + context: Context, + ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationPublicKey: CipherParameters, + staticKeyPair: AsymmetricCipherKeyPair, + info: ByteArray, + headerInfo: ByteArray, + ) : NoiseIKKey { + val protocols = Protocols(context) + + var h = "Noise_IK_25519_AESGCM_SHA256".encodeToByteArray().sha256() + var ck = h + + h = (h + (authenticationPublicKey as X25519PublicKeyParameters).encoded).sha256() + h = (h + (ephemeralKeyPair.public as X25519PublicKeyParameters).encoded).sha256() + + val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + + return hkdf( + ikm = dhEs, + salt = ck, + info = info, + len = 2 + ).run { + ck = this.sliceArray(0 until 32) + var k = this.sliceArray(32 until 64) + val csPkEnc = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + (staticKeyPair.public as X25519PublicKeyParameters).encoded, + h + ) + h = (h + csPkEnc).sha256() + val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) + + hkdf( + ikm = dhSs, + salt = ck, + info = info, + len = 2 + ).run { + ck = this.sliceArray(0 until 32) + k = this.sliceArray(32 until 64) + val ciphertext = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + h + ) + h = (h + ciphertext).sha256() + + hkdf( + ikm = dhSs, + salt = ck, + info = headerInfo, + len = 3 + ).run { + NoiseIKKey( + Triple( + this.sliceArray(0 until 32), + this.sliceArray(32 until 64), + this.sliceArray(64 until 96), + ), + h + ) + } + } + } + } + + fun generateKeysIKForwardSecrecy( + context: Context, + h: ByteArray, + ck: ByteArray, + ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralResponderPublicKey: CipherParameters, + authenticationPublicKey: CipherParameters, + info: ByteArray, + headerInfo: ByteArray, + ) : NoiseIKKey{ + val protocols = Protocols(context) + + var h = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() + val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) + + return hkdf( + ikm = dhEe, + salt = ck, + info = info, + len = 2 + ).run { + var ck = this.sliceArray(0 until 32) + var k = this.sliceArray(32 until 64) + var ciphertext = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + h + ) + h = (h + ciphertext).sha256() + val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + hkdf( + ikm = dhSe, + salt = ck, + info = info, + len = 2 + ).run { + ck = this.sliceArray(0 until 32) + k = this.sliceArray(32 until 64) + ciphertext = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + h + ) + h = (h + ciphertext).sha256() + + hkdf( + ikm = "".encodeToByteArray(), + salt = ck, + info = headerInfo, + len = 3 + ).run { + NoiseIKKey( + Triple( + this.sliceArray(0 until 32), + this.sliceArray(32 until 64), + this.sliceArray(64 until 96), + ), + h + ) + } + } + } + } + fun ByteArray.sha256(): ByteArray { return MessageDigest .getInstance("SHA-256") diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt new file mode 100644 index 0000000..152ae98 --- /dev/null +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -0,0 +1,77 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet + +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import java.security.SecureRandom + +object Cryptography { + + object AesGcm { + private const val ALGORITHM = "AES/GCM/NoPadding" + private const val KEY_SIZE_BITS = 256 + private const val IV_SIZE_BYTES = 12 // 96-bit IV recommended for GCM + private const val TAG_SIZE_BITS = 128 // authentication tag length + + data class CipherResult( + val ciphertext: ByteArray, // encrypted data (includes appended GCM auth tag) + val iv: ByteArray // IV — must be stored alongside ciphertext for decryption + ) + + fun generateKey(): SecretKey { + val keygen = KeyGenerator.getInstance("AES") + keygen.init(KEY_SIZE_BITS, SecureRandom()) + return keygen.generateKey() + } + + /** + * Encrypts [plaintext] with AES-256-GCM. + * + * @param key AES secret key (128, 192, or 256-bit) + * @param plaintext Data to encrypt + * @param associatedData AAD: authenticated but NOT encrypted (e.g. headers, context). + * Pass null if not needed. + * @return CipherResult containing the ciphertext+tag and the IV used. + */ + fun encrypt( + key: SecretKey, + plaintext: ByteArray, + associatedData: ByteArray? = null + ): ByteArray { + val iv = ByteArray(IV_SIZE_BYTES).also { SecureRandom().nextBytes(it) } + val spec = GCMParameterSpec(TAG_SIZE_BITS, iv) + + val cipher = Cipher.getInstance(ALGORITHM) + cipher.init(Cipher.ENCRYPT_MODE, key, spec) + associatedData?.let { cipher.updateAAD(it) } + + val ciphertext = cipher.doFinal(plaintext) + return iv + ciphertext + } + + /** + * Decrypts and authenticates output from [encrypt]. + * Throws [javax.crypto.AEADBadTagException] if the tag or AAD doesn't match. + * + * @param key Same AES key used during encryption + * @param ciphertext Encrypted bytes (ciphertext + appended GCM tag) + * @param iv IV from the corresponding [CipherResult] + * @param associatedData Must be identical to the AAD used during encryption + */ + fun decrypt( + key: SecretKey, + ciphertext: ByteArray, + iv: ByteArray, + associatedData: ByteArray? = null + ): ByteArray { + val spec = GCMParameterSpec(TAG_SIZE_BITS, iv) + + val cipher = Cipher.getInstance(ALGORITHM) + cipher.init(Cipher.DECRYPT_MODE, key, spec) + associatedData?.let { cipher.updateAAD(it) } + + return cipher.doFinal(ciphertext) + } + } +} \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt deleted file mode 100644 index 26e3f7a..0000000 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/EncryptionController.kt +++ /dev/null @@ -1,347 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.content.Context -import android.util.Base64 -import android.widget.Toast -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.core.stringPreferencesKey -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.dataStore -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getEncryptedBinaryData -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.getKeypairValues -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.saveBinaryDataEncrypted -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.setKeypairValues -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Headers -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.States -import com.google.gson.Gson -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import kotlinx.serialization.Serializable - -//object EncryptionController { -// -// @Serializable -// enum class SecureRequestMode { -// REQUEST_NONE, -// REQUEST_REQUESTED, -// REQUEST_RECEIVED, -// REQUEST_ACCEPTED, -// } -// -// enum class MessageRequestType(val code: Byte) { -// TYPE_REQUEST(0x01.toByte()), -// TYPE_ACCEPT(0x02.toByte()), -// TYPE_MESSAGE(0x03.toByte()); -// -// companion object { -// fun fromCode(code: Byte): MessageRequestType? = -// entries.find { it.code == code } // Kotlin 1.9+, use values() before that -// -// fun fromMessage(message: ByteArray): MessageRequestType? = -// entries.find { it.code == message[0] } // Kotlin 1.9+, use values() before that -// } -// } -// -// private fun extractRequestPublicKey( publicKey: ByteArray) : ByteArray { -// val lenPubKey = publicKey[1].toInt() -// return publicKey.drop(2).toByteArray() -// } -// -// private fun extractMessage(data: ByteArray) : Pair { -// val lenHeader = data[1].toInt() -// val lenMessage = data[2].toInt() -// val header = data.copyOfRange(3, 3 + lenHeader) -// val message = data.copyOfRange(3 + lenHeader, (3 + lenHeader + lenMessage)) -// return Pair(Headers.deserialize(header), message) -// } -// -// @OptIn(ExperimentalUnsignedTypes::class) -// private fun formatRequestPublicKey( -// publicKey: ByteArray, -// type: MessageRequestType -// ) : ByteArray { -// val mn = ubyteArrayOf(type.code.toUByte()) -// val lenPubKey = ubyteArrayOf(publicKey.size.toUByte()) -// -// return (mn + lenPubKey).toByteArray() + publicKey -// } -// -// @OptIn(ExperimentalUnsignedTypes::class) -// private fun formatMessage( -// header: Headers, -// cipherText: ByteArray -// ) : ByteArray { -// val mn = ubyteArrayOf(MessageRequestType.TYPE_MESSAGE.code.toUByte()) -// val lenHeader = ubyteArrayOf(header.serialized.size.toUByte()) -// val lenMessage = ubyteArrayOf(cipherText.size.toUByte()) -// -// return (mn + lenHeader + lenMessage).toByteArray() + header.serialized + cipherText -// } -// -// suspend fun sendRequest( -// context: Context, -// address: String, -// mode: SecureRequestMode, -// ): ByteArray { -// try { -// val publicKey = generateIdentityPublicKeys(context, address) -// -// var type: MessageRequestType? = null -// val mode = when(mode) { -// SecureRequestMode.REQUEST_RECEIVED -> { -// type = MessageRequestType.TYPE_ACCEPT -// SecureRequestMode.REQUEST_ACCEPTED -// } -// else -> { -// type = MessageRequestType.TYPE_REQUEST -// SecureRequestMode.REQUEST_REQUESTED -// } -// } -// -// context.setEncryptionModeStates(address, mode) -// return formatRequestPublicKey(publicKey, type) -// } catch (e: Exception) { -// throw e -// } -// } -// -// suspend fun receiveRequest( -// context: Context, -// address: String, -// publicKey: ByteArray, -// ) : ByteArray? { -// MessageRequestType.fromCode(publicKey[0])?.let { type -> -// val publicKey = extractRequestPublicKey(publicKey) -// try { -// val mode = when(type) { -// MessageRequestType.TYPE_REQUEST -> { -// SecureRequestMode.REQUEST_RECEIVED -// } -// MessageRequestType.TYPE_ACCEPT -> { -// context.removeEncryptionRatchetStates(address) -// SecureRequestMode.REQUEST_ACCEPTED -// } -// else -> return null -// } -// context.setEncryptionModeStates( -// address, -// mode, -// publicKey, -// ) -// } catch (e: Exception) { -// throw e -// } -// return publicKey -// } -// -// return null -// } -// -// @Throws -// private suspend fun generateIdentityPublicKeys( -// context: Context, -// address: String -// ): ByteArray { -// try { -// val libSigCurve25519 = SecurityCurve25519() -// val publicKey = libSigCurve25519.generateKey() -// context.setKeypairValues(address, publicKey, libSigCurve25519.privateKey) -// return publicKey -// } catch (e: Exception) { -// throw e -// } -// } -// -// @Throws -// suspend fun decrypt( -// context: Context, -// address: String, -// text: String -// ): String? { -// -// val data = Base64.decode(text, Base64.DEFAULT) -// if(MessageRequestType.fromCode(data[0]) != MessageRequestType.TYPE_MESSAGE) -// return null -// -// val payload = try { extractMessage(data) } catch(e: Exception) { -// throw e -// } -// -// val modeStates = context.getEncryptionModeStatesSync(address) -// val publicKey = Gson().fromJson(modeStates, -// SavedEncryptedModes::class.java).publicKey -// -// if(publicKey == null) { -// CoroutineScope(Dispatchers.Main).launch { -// Toast.makeText( -// context, -// context.getString(R.string.missing_public_key), -// Toast.LENGTH_LONG).show() -// } -// return null -// } -// -// val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) -// -// val keystore = address + "_ratchet_state" -// val currentState = context.getEncryptedBinaryData(keystore) -// -// var state: States? -// if(currentState == null) { -// state = States() -// val sk = context.calculateSharedSecret(address, publicKeyBytes) -// val keypair = context.getKeypairValues(address) //public private -// -// Ratchets.ratchetInitBob( -// state, -// sk, -// android.util.Pair(keypair.second, keypair.first) -// ) -// } -// else state = States.deserialize(String(currentState)) -// -// val keypair = context.getKeypairValues(address) -// var decryptedText: String? -// try { -// decryptedText = String(Ratchets.ratchetDecrypt( -// state, -// payload.first, -// payload.second, -// keypair.first -// )) -// context.saveBinaryDataEncrypted(keystore, -// state.serialize().encodeToByteArray()) -// } catch(e: Exception) { -// throw e -// } -// return decryptedText -// } -// -// @Throws -// suspend fun encrypt( -// context: Context, -// address: String, -// text: String -// ) : String? { -// val modeStates = context.getEncryptionModeStatesSync(address) -// val publicKey = Gson().fromJson(modeStates, -// SavedEncryptedModes::class.java).publicKey -// -// if(publicKey == null) { -// CoroutineScope(Dispatchers.Main).launch { -// Toast.makeText( -// context, -// context.getString(R.string.missing_public_key), -// Toast.LENGTH_LONG).show() -// } -// return null -// } -// -// val publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT) -// -// val keystore = address + "_ratchet_state" -// val currentState = context.getEncryptedBinaryData(keystore) -// -// var state: States? -// if(currentState == null) { -// state = States() -// val sk = context.calculateSharedSecret(address, publicKeyBytes) -// Ratchets.ratchetInitAlice(state, sk, publicKeyBytes) -// } -// else state = States.deserialize(String(currentState)) -// -// val ratchetOutput = Ratchets.ratchetEncrypt(state, -// text.encodeToByteArray(), publicKeyBytes) -// -// return try { -// val message = formatMessage( -// ratchetOutput.first, -// ratchetOutput.second -// ) -// context.saveBinaryDataEncrypted(keystore, -// state.serialize().encodeToByteArray()) -// Base64.encodeToString(message, Base64.DEFAULT) -// } catch(e: Exception) { -// throw e -// } -// } -//} -// -//private suspend fun Context.calculateSharedSecret( -// address: String, -// publicKey: ByteArray -//): ByteArray? { -// val keypair = getKeypairValues(address) //public private -// keypair.second?.let { privateKey -> -// val libSigCurve25519 = SecurityCurve25519(privateKey) -// return libSigCurve25519.calculateSharedSecret(publicKey) -// } -// return null -//} -// -//data class SavedEncryptedModes( -// var mode: EncryptionController.SecureRequestMode, -// var publicKey: String? = null, -//) -// -//private suspend fun Context.setEncryptionModeStates( -// address: String, -// mode: EncryptionController.SecureRequestMode, -// publicKey: ByteArray? = null, -//) { -// val keyValue = stringPreferencesKey(address + "_mode_states") -// dataStore.edit { secureComms -> -// // Make a mutable copy of existing state -// val currentState = secureComms[keyValue] ?: "" -// val savedEncryptedModes = if(currentState.isNotEmpty()) Gson() -// .fromJson(currentState, SavedEncryptedModes::class.java) -// .apply { this.mode = mode } -// else SavedEncryptedModes(mode = mode) -// -// publicKey?.let { publicKey -> -// savedEncryptedModes.publicKey = -// Base64.encodeToString(publicKey, Base64.DEFAULT) -// } -// -// secureComms[keyValue] = Gson().toJson(savedEncryptedModes) -// } -//} -// -//suspend fun Context.removeEncryptionRatchetStates(address: String) { -// val keyValue = stringPreferencesKey(address + "_ratchet_state") -// dataStore.edit { secureComms -> -// secureComms.remove(keyValue) -// withContext(Dispatchers.Main) { -// Toast.makeText( -// this@removeEncryptionRatchetStates, -// getString(R.string.ratchet_states_removed), -// Toast.LENGTH_LONG).show() -// } -// } -//} -// -//suspend fun Context.removeEncryptionModeStates(address: String) { -// val keyValue = stringPreferencesKey(address + "_mode_states") -// dataStore.edit { secureComms -> -// secureComms.remove(keyValue) -// } -//} -// -//fun Context.getEncryptionRatchetStates(address: String): Flow { -// val keyValue = stringPreferencesKey(address + "_ratchet_state") -// return dataStore.data.map { it[keyValue] } -//} -// -//suspend fun Context.getEncryptionModeStatesSync(address: String): String? { -// val keyValue = stringPreferencesKey(address + "_mode_states") -// return dataStore.data.first()[keyValue] -//} -// -//fun Context.getEncryptionModeStates(address: String): Flow { -// val keyValue = stringPreferencesKey(address + "_mode_states") -// return dataStore.data.map { it[keyValue] } -//} From 913b64689e0ba31341891b636ba239eab95f8d8a Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 12:25:52 +0100 Subject: [PATCH 09/19] update: zeroed out for sec --- .../libsignal_doubleratchet/CryptoUtils.kt | 200 ++++++++++-------- 1 file changed, 113 insertions(+), 87 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt index 6f8b648..8ab9e07 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -126,54 +126,62 @@ object CryptoUtils { h = (h + (ephemeralKeyPair.public as X25519PublicKeyParameters).encoded).sha256() val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) - return hkdf( - ikm = dhEs, - salt = ck, - info = info, - len = 2 - ).run { - ck = this.sliceArray(0 until 32) - var k = this.sliceArray(32 until 64) - val csPkEnc = Cryptography.AesGcm.encrypt( + // Named references so we can zero them + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + var hkdf3: ByteArray? = null + var k: ByteArray? = null + var csPkEnc: ByteArray? = null + var ciphertext: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dhEs, salt = ck, info = info, len = 2) + ck = hkdf1.sliceArray(0 until 32) + k = hkdf1.sliceArray(32 until 64) + + csPkEnc = Cryptography.AesGcm.encrypt( SecretKeySpec(k, "AES"), (staticKeyPair.public as X25519PublicKeyParameters).encoded, h ) h = (h + csPkEnc).sha256() - val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) - hkdf( - ikm = dhSs, - salt = ck, - info = info, - len = 2 - ).run { - ck = this.sliceArray(0 until 32) - k = this.sliceArray(32 until 64) - val ciphertext = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - "".encodeToByteArray(), - h - ) - h = (h + ciphertext).sha256() - - hkdf( - ikm = dhSs, - salt = ck, - info = headerInfo, - len = 3 - ).run { - NoiseIKKey( - Triple( - this.sliceArray(0 until 32), - this.sliceArray(32 until 64), - this.sliceArray(64 until 96), - ), - h - ) - } - } + hkdf2 = hkdf(ikm = dhSs, salt = ck, info = info, len = 2) + ck = hkdf2.sliceArray(0 until 32) + k.fill(0) // zero previous k before reassigning + k = hkdf2.sliceArray(32 until 64) + + ciphertext = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + h + ) + h = (h + ciphertext).sha256() + + hkdf3 = hkdf(ikm = dhSs, salt = ck, info = headerInfo, len = 3) + + return NoiseIKKey( + Triple( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), + ), + h + ) + } finally { + // Zero everything sensitive regardless of success or exception + dhEs.fill(0) + dhSs.fill(0) + ck.fill(0) + k?.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + hkdf3?.fill(0) + // csPkEnc and ciphertext are non-secret ciphertext, but zero anyway + csPkEnc?.fill(0) + ciphertext?.fill(0) } } @@ -186,61 +194,79 @@ object CryptoUtils { authenticationPublicKey: CipherParameters, info: ByteArray, headerInfo: ByteArray, - ) : NoiseIKKey{ + ) : NoiseIKKey { val protocols = Protocols(context) - var h = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() + // Shadowed vars — use local mutable copies so we can zero them + // Note: the incoming h and ck are owned by the caller; don't zero them here + var localH = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() + var localCk = ck.copyOf() // defensive copy — we'll mutate and zero this + val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) + val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - return hkdf( - ikm = dhEe, - salt = ck, - info = info, - len = 2 - ).run { - var ck = this.sliceArray(0 until 32) - var k = this.sliceArray(32 until 64) - var ciphertext = Cryptography.AesGcm.encrypt( + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + var hkdf3: ByteArray? = null + var k: ByteArray? = null + var ciphertext1: ByteArray? = null + var ciphertext2: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dhEe, salt = localCk, info = info, len = 2) + localCk.fill(0) + localCk = hkdf1.sliceArray(0 until 32) + k = hkdf1.sliceArray(32 until 64) + + ciphertext1 = Cryptography.AesGcm.encrypt( SecretKeySpec(k, "AES"), "".encodeToByteArray(), - h + localH ) - h = (h + ciphertext).sha256() - val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - hkdf( - ikm = dhSe, - salt = ck, - info = info, - len = 2 - ).run { - ck = this.sliceArray(0 until 32) - k = this.sliceArray(32 until 64) - ciphertext = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - "".encodeToByteArray(), - h - ) - h = (h + ciphertext).sha256() - - hkdf( - ikm = "".encodeToByteArray(), - salt = ck, - info = headerInfo, - len = 3 - ).run { - NoiseIKKey( - Triple( - this.sliceArray(0 until 32), - this.sliceArray(32 until 64), - this.sliceArray(64 until 96), - ), - h - ) - } - } + localH = (localH + ciphertext1).sha256() + + hkdf2 = hkdf(ikm = dhSe, salt = localCk, info = info, len = 2) + localCk.fill(0) + localCk = hkdf2.sliceArray(0 until 32) + k.fill(0) // zero previous k before reassign + k = hkdf2.sliceArray(32 until 64) + + ciphertext2 = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + localH + ) + localH = (localH + ciphertext2).sha256() + + hkdf3 = hkdf( + ikm = "".encodeToByteArray(), + salt = localCk, + info = headerInfo, + len = 3 + ) + + return NoiseIKKey( + Triple( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), + ), + localH + ) + } finally { + dhEe.fill(0) + dhSe.fill(0) + localCk.fill(0) + k?.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + hkdf3?.fill(0) + ciphertext1?.fill(0) + ciphertext2?.fill(0) + // Do NOT zero localH — it's returned inside NoiseIKKey + // Do NOT zero the caller's h and ck — we don't own them } } - fun ByteArray.sha256(): ByteArray { return MessageDigest .getInstance("SHA-256") From f122de37e312c9e4e9ed53af5fba204bb182341a Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 12:30:26 +0100 Subject: [PATCH 10/19] update: zeroed out for sec --- .../libsignal_doubleratchet/CryptoUtils.kt | 76 ++++++++++--------- 1 file changed, 39 insertions(+), 37 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt index 8ab9e07..5c724c3 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -49,29 +49,31 @@ object CryptoUtils { info: ByteArray, ): Triple { val protocols = Protocols(context) + val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) - return hkdf( - ikm = dh1, - salt = salt, - info = info, - len = 32, - ).run { - hkdf( - ikm = dh2, - salt = this, - info = info, - len = 96, - ).run { - Triple( - this.sliceArray(0 until 32), - this.sliceArray(32 until 64), - this.sliceArray(64 until 96), - ) - } + + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dh1, salt = salt, info = info, len = 32) + hkdf2 = hkdf(ikm = dh2, salt = hkdf1, info = info, len = 96) + + return Triple( + hkdf2.sliceArray(0 until 32), + hkdf2.sliceArray(32 until 64), + hkdf2.sliceArray(64 until 96), + ) + } finally { + dh1.fill(0) + dh2.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + // The sliceArray copies inside Triple are intentionally not zeroed — + // they are the return value and owned by the caller } } - fun generateKeysNKServer( context: Context, authenticationKeypair: AsymmetricCipherKeyPair, @@ -83,24 +85,24 @@ object CryptoUtils { val protocols = Protocols(context) val dh1 = protocols.dh(authenticationKeypair, ephemeralPublicKey) val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) - return hkdf( - ikm = dh1, - salt = salt, - info = info, - len = 32, - ).run { - hkdf( - ikm = dh2, - salt = this, - info = info, - len = 96, - ).run { - Triple( - this.sliceArray(0 until 32), - this.sliceArray(32 until 64), - this.sliceArray(64 until 96), - ) - } + + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + + try { + hkdf1 = hkdf( ikm = dh1, salt = salt, info = info, len = 32, ) + hkdf2 = hkdf( ikm = dh2, salt = hkdf1, info = info, len = 96, ) + + return Triple( + hkdf2.sliceArray(0 until 32), + hkdf2.sliceArray(32 until 64), + hkdf2.sliceArray(64 until 96), + ) + } finally { + dh1.fill(0) + dh2.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) } } From 4e543dcd5a29fdb839769023bd6389f73c2775c8 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 12:56:40 +0100 Subject: [PATCH 11/19] update: refactored --- .../libsignal/RatchetsTest.kt | 5 +- .../libsignal_doubleratchet/CryptoUtils.kt | 229 ----------------- .../libsignal_doubleratchet/Cryptography.kt | 238 ++++++++++++++++++ 3 files changed, 241 insertions(+), 231 deletions(-) diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index e4a60aa..89093d2 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -5,6 +5,7 @@ import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.sha256 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.Cryptography import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.generateRandomBytes import org.bouncycastle.crypto.params.X25519PublicKeyParameters import org.junit.Assert.assertArrayEquals @@ -38,7 +39,7 @@ class RatchetsTest { @Before fun start() { - CryptoUtils.generateKeysNK( + Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, authenticationPublicKey = bobStaticKeypair.public, @@ -51,7 +52,7 @@ class RatchetsTest { aliceNhk = it.third } - CryptoUtils.generateKeysNKServer( + Cryptography.generateKeysNKServer( context = context, authenticationKeypair = bobStaticKeypair, ephemeralKeyPair = bobKeypair, diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt index 5c724c3..eb4ddf8 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/CryptoUtils.kt @@ -40,235 +40,6 @@ object CryptoUtils { return output } - fun generateKeysNK( - context: Context, - ephemeralKeyPair: AsymmetricCipherKeyPair, - authenticationPublicKey: CipherParameters, - ephemeralPublicKey: CipherParameters, - salt: ByteArray, - info: ByteArray, - ): Triple { - val protocols = Protocols(context) - - val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) - - var hkdf1: ByteArray? = null - var hkdf2: ByteArray? = null - - try { - hkdf1 = hkdf(ikm = dh1, salt = salt, info = info, len = 32) - hkdf2 = hkdf(ikm = dh2, salt = hkdf1, info = info, len = 96) - - return Triple( - hkdf2.sliceArray(0 until 32), - hkdf2.sliceArray(32 until 64), - hkdf2.sliceArray(64 until 96), - ) - } finally { - dh1.fill(0) - dh2.fill(0) - hkdf1?.fill(0) - hkdf2?.fill(0) - // The sliceArray copies inside Triple are intentionally not zeroed — - // they are the return value and owned by the caller - } - } - fun generateKeysNKServer( - context: Context, - authenticationKeypair: AsymmetricCipherKeyPair, - ephemeralKeyPair: AsymmetricCipherKeyPair, - ephemeralPublicKey: CipherParameters, - salt: ByteArray, - info: ByteArray, - ): Triple { - val protocols = Protocols(context) - val dh1 = protocols.dh(authenticationKeypair, ephemeralPublicKey) - val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) - - var hkdf1: ByteArray? = null - var hkdf2: ByteArray? = null - - try { - hkdf1 = hkdf( ikm = dh1, salt = salt, info = info, len = 32, ) - hkdf2 = hkdf( ikm = dh2, salt = hkdf1, info = info, len = 96, ) - - return Triple( - hkdf2.sliceArray(0 until 32), - hkdf2.sliceArray(32 until 64), - hkdf2.sliceArray(64 until 96), - ) - } finally { - dh1.fill(0) - dh2.fill(0) - hkdf1?.fill(0) - hkdf2?.fill(0) - } - } - - data class NoiseIKKey( - val keys: Triple, - val h: ByteArray - ) - - fun generateKeysIK( - context: Context, - ephemeralKeyPair: AsymmetricCipherKeyPair, - authenticationPublicKey: CipherParameters, - staticKeyPair: AsymmetricCipherKeyPair, - info: ByteArray, - headerInfo: ByteArray, - ) : NoiseIKKey { - val protocols = Protocols(context) - - var h = "Noise_IK_25519_AESGCM_SHA256".encodeToByteArray().sha256() - var ck = h - - h = (h + (authenticationPublicKey as X25519PublicKeyParameters).encoded).sha256() - h = (h + (ephemeralKeyPair.public as X25519PublicKeyParameters).encoded).sha256() - - val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) - - // Named references so we can zero them - var hkdf1: ByteArray? = null - var hkdf2: ByteArray? = null - var hkdf3: ByteArray? = null - var k: ByteArray? = null - var csPkEnc: ByteArray? = null - var ciphertext: ByteArray? = null - - try { - hkdf1 = hkdf(ikm = dhEs, salt = ck, info = info, len = 2) - ck = hkdf1.sliceArray(0 until 32) - k = hkdf1.sliceArray(32 until 64) - - csPkEnc = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - (staticKeyPair.public as X25519PublicKeyParameters).encoded, - h - ) - h = (h + csPkEnc).sha256() - - hkdf2 = hkdf(ikm = dhSs, salt = ck, info = info, len = 2) - ck = hkdf2.sliceArray(0 until 32) - k.fill(0) // zero previous k before reassigning - k = hkdf2.sliceArray(32 until 64) - - ciphertext = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - "".encodeToByteArray(), - h - ) - h = (h + ciphertext).sha256() - - hkdf3 = hkdf(ikm = dhSs, salt = ck, info = headerInfo, len = 3) - - return NoiseIKKey( - Triple( - hkdf3.sliceArray(0 until 32), - hkdf3.sliceArray(32 until 64), - hkdf3.sliceArray(64 until 96), - ), - h - ) - } finally { - // Zero everything sensitive regardless of success or exception - dhEs.fill(0) - dhSs.fill(0) - ck.fill(0) - k?.fill(0) - hkdf1?.fill(0) - hkdf2?.fill(0) - hkdf3?.fill(0) - // csPkEnc and ciphertext are non-secret ciphertext, but zero anyway - csPkEnc?.fill(0) - ciphertext?.fill(0) - } - } - - fun generateKeysIKForwardSecrecy( - context: Context, - h: ByteArray, - ck: ByteArray, - ephemeralKeyPair: AsymmetricCipherKeyPair, - ephemeralResponderPublicKey: CipherParameters, - authenticationPublicKey: CipherParameters, - info: ByteArray, - headerInfo: ByteArray, - ) : NoiseIKKey { - val protocols = Protocols(context) - - // Shadowed vars — use local mutable copies so we can zero them - // Note: the incoming h and ck are owned by the caller; don't zero them here - var localH = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() - var localCk = ck.copyOf() // defensive copy — we'll mutate and zero this - - val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) - val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - - var hkdf1: ByteArray? = null - var hkdf2: ByteArray? = null - var hkdf3: ByteArray? = null - var k: ByteArray? = null - var ciphertext1: ByteArray? = null - var ciphertext2: ByteArray? = null - - try { - hkdf1 = hkdf(ikm = dhEe, salt = localCk, info = info, len = 2) - localCk.fill(0) - localCk = hkdf1.sliceArray(0 until 32) - k = hkdf1.sliceArray(32 until 64) - - ciphertext1 = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - "".encodeToByteArray(), - localH - ) - localH = (localH + ciphertext1).sha256() - - hkdf2 = hkdf(ikm = dhSe, salt = localCk, info = info, len = 2) - localCk.fill(0) - localCk = hkdf2.sliceArray(0 until 32) - k.fill(0) // zero previous k before reassign - k = hkdf2.sliceArray(32 until 64) - - ciphertext2 = Cryptography.AesGcm.encrypt( - SecretKeySpec(k, "AES"), - "".encodeToByteArray(), - localH - ) - localH = (localH + ciphertext2).sha256() - - hkdf3 = hkdf( - ikm = "".encodeToByteArray(), - salt = localCk, - info = headerInfo, - len = 3 - ) - - return NoiseIKKey( - Triple( - hkdf3.sliceArray(0 until 32), - hkdf3.sliceArray(32 until 64), - hkdf3.sliceArray(64 until 96), - ), - localH - ) - } finally { - dhEe.fill(0) - dhSe.fill(0) - localCk.fill(0) - k?.fill(0) - hkdf1?.fill(0) - hkdf2?.fill(0) - hkdf3?.fill(0) - ciphertext1?.fill(0) - ciphertext2?.fill(0) - // Do NOT zero localH — it's returned inside NoiseIKKey - // Do NOT zero the caller's h and ck — we don't own them - } - } fun ByteArray.sha256(): ByteArray { return MessageDigest .getInstance("SHA-256") diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index 152ae98..504fa0c 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -1,13 +1,251 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet +import android.content.Context +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hkdf +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.sha256 +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols +import org.bouncycastle.crypto.AsymmetricCipherKeyPair +import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.params.X25519PublicKeyParameters import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import java.security.SecureRandom +import javax.crypto.spec.SecretKeySpec object Cryptography { + fun generateKeysNK( + context: Context, + ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationPublicKey: CipherParameters, + ephemeralPublicKey: CipherParameters, + salt: ByteArray, + info: ByteArray, + ): Triple { + val protocols = Protocols(context) + + val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dh1, salt = salt, info = info, len = 32) + hkdf2 = hkdf(ikm = dh2, salt = hkdf1, info = info, len = 96) + + return Triple( + hkdf2.sliceArray(0 until 32), + hkdf2.sliceArray(32 until 64), + hkdf2.sliceArray(64 until 96), + ) + } finally { + dh1.fill(0) + dh2.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + // The sliceArray copies inside Triple are intentionally not zeroed — + // they are the return value and owned by the caller + } + } + fun generateKeysNKServer( + context: Context, + authenticationKeypair: AsymmetricCipherKeyPair, + ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralPublicKey: CipherParameters, + salt: ByteArray, + info: ByteArray, + ): Triple { + val protocols = Protocols(context) + val dh1 = protocols.dh(authenticationKeypair, ephemeralPublicKey) + val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + + try { + hkdf1 = hkdf( ikm = dh1, salt = salt, info = info, len = 32, ) + hkdf2 = hkdf( ikm = dh2, salt = hkdf1, info = info, len = 96, ) + + return Triple( + hkdf2.sliceArray(0 until 32), + hkdf2.sliceArray(32 until 64), + hkdf2.sliceArray(64 until 96), + ) + } finally { + dh1.fill(0) + dh2.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + } + } + + data class NoiseIKKey( + val keys: Triple, + val h: ByteArray + ) + + fun generateKeysIK( + context: Context, + ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationPublicKey: CipherParameters, + staticKeyPair: AsymmetricCipherKeyPair, + info: ByteArray, + headerInfo: ByteArray, + ) : NoiseIKKey { + val protocols = Protocols(context) + + var h = "Noise_IK_25519_AESGCM_SHA256".encodeToByteArray().sha256() + var ck = h + + h = (h + (authenticationPublicKey as X25519PublicKeyParameters).encoded).sha256() + h = (h + (ephemeralKeyPair.public as X25519PublicKeyParameters).encoded).sha256() + + val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) + + // Named references so we can zero them + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + var hkdf3: ByteArray? = null + var k: ByteArray? = null + var csPkEnc: ByteArray? = null + var ciphertext: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dhEs, salt = ck, info = info, len = 2) + ck = hkdf1.sliceArray(0 until 32) + k = hkdf1.sliceArray(32 until 64) + + csPkEnc = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + (staticKeyPair.public as X25519PublicKeyParameters).encoded, + h + ) + h = (h + csPkEnc).sha256() + + hkdf2 = hkdf(ikm = dhSs, salt = ck, info = info, len = 2) + ck = hkdf2.sliceArray(0 until 32) + k.fill(0) // zero previous k before reassigning + k = hkdf2.sliceArray(32 until 64) + + ciphertext = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + h + ) + h = (h + ciphertext).sha256() + + hkdf3 = hkdf(ikm = dhSs, salt = ck, info = headerInfo, len = 3) + + return NoiseIKKey( + Triple( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), + ), + h + ) + } finally { + // Zero everything sensitive regardless of success or exception + dhEs.fill(0) + dhSs.fill(0) + ck.fill(0) + k?.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + hkdf3?.fill(0) + // csPkEnc and ciphertext are non-secret ciphertext, but zero anyway + csPkEnc?.fill(0) + ciphertext?.fill(0) + } + } + + fun generateKeysIKForwardSecrecy( + context: Context, + h: ByteArray, + ck: ByteArray, + ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralResponderPublicKey: CipherParameters, + authenticationPublicKey: CipherParameters, + info: ByteArray, + headerInfo: ByteArray, + ) : NoiseIKKey { + val protocols = Protocols(context) + + // Shadowed vars — use local mutable copies so we can zero them + // Note: the incoming h and ck are owned by the caller; don't zero them here + var localH = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() + var localCk = ck.copyOf() // defensive copy — we'll mutate and zero this + + val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) + val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + + var hkdf1: ByteArray? = null + var hkdf2: ByteArray? = null + var hkdf3: ByteArray? = null + var k: ByteArray? = null + var ciphertext1: ByteArray? = null + var ciphertext2: ByteArray? = null + + try { + hkdf1 = hkdf(ikm = dhEe, salt = localCk, info = info, len = 2) + localCk.fill(0) + localCk = hkdf1.sliceArray(0 until 32) + k = hkdf1.sliceArray(32 until 64) + + ciphertext1 = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + localH + ) + localH = (localH + ciphertext1).sha256() + + hkdf2 = hkdf(ikm = dhSe, salt = localCk, info = info, len = 2) + localCk.fill(0) + localCk = hkdf2.sliceArray(0 until 32) + k.fill(0) // zero previous k before reassign + k = hkdf2.sliceArray(32 until 64) + + ciphertext2 = Cryptography.AesGcm.encrypt( + SecretKeySpec(k, "AES"), + "".encodeToByteArray(), + localH + ) + localH = (localH + ciphertext2).sha256() + + hkdf3 = hkdf( + ikm = "".encodeToByteArray(), + salt = localCk, + info = headerInfo, + len = 3 + ) + + return NoiseIKKey( + Triple( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), + ), + localH + ) + } finally { + dhEe.fill(0) + dhSe.fill(0) + localCk.fill(0) + k?.fill(0) + hkdf1?.fill(0) + hkdf2?.fill(0) + hkdf3?.fill(0) + ciphertext1?.fill(0) + ciphertext2?.fill(0) + // Do NOT zero localH — it's returned inside NoiseIKKey + // Do NOT zero the caller's h and ck — we don't own them + } + } + object AesGcm { private const val ALGORITHM = "AES/GCM/NoPadding" private const val KEY_SIZE_BITS = 256 From 942f310efa93187dcfcd16a44c1b816a3bfab41f Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 14:23:36 +0100 Subject: [PATCH 12/19] update: making use of use to zero out keys --- .../libsignal/RatchetsTest.kt | 312 ++++++++++-------- .../libsignal_doubleratchet/Cryptography.kt | 88 +++-- .../libsignal/RatchetsHE.kt | 98 ++++-- 3 files changed, 305 insertions(+), 193 deletions(-) diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index 89093d2..35b03d7 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -19,14 +19,6 @@ class RatchetsTest { InstrumentationRegistry.getInstrumentation().targetContext val protocol = Protocols(context) - lateinit var aliceRk: ByteArray - lateinit var aliceHk: ByteArray - lateinit var aliceNhk: ByteArray - - lateinit var bobRk: ByteArray - lateinit var bobHk: ByteArray - lateinit var bobNhk: ByteArray - val aliceKeypair = protocol.generateDH() val bobStaticKeypair = protocol.generateDH() val bobKeypair = protocol.generateDH() @@ -37,8 +29,8 @@ class RatchetsTest { (bobKeypair.public as X25519PublicKeyParameters).encoded + (bobStaticKeypair.public as X25519PublicKeyParameters).encoded - @Before - fun start() { + @Test + fun completeRatchetTest() { Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, @@ -46,145 +38,185 @@ class RatchetsTest { ephemeralPublicKey = bobKeypair.public, salt = salt, info = info - ).let { - aliceRk = it.first - aliceHk = it.second - aliceNhk = it.third - } + ).use { alice -> + Cryptography.generateKeysNKServer( + context = context, + authenticationKeypair = bobStaticKeypair, + ephemeralKeyPair = bobKeypair, + ephemeralPublicKey = aliceKeypair.public, + salt = salt, + info = info + ).let { bob -> + assertArrayEquals(alice.rk, bob.first) + assertArrayEquals(alice.hk, bob.second) + assertArrayEquals(alice.nhk, bob.third) + + val ratchets = RatchetsHE(context) + val aliceState = States() + ratchets.ratchetInitAlice( + state = aliceState, + sk = alice.rk, + bobDhPublicKey = bobKeypair.public, + sharedHka = alice.hk, + sharedNHka = alice.nhk + ) + + val bobState = States() + ratchets.ratchetInitBob( + state = bobState, + sk = bob.first, + bobKeypair = bobKeypair, + sharedHka = bob.second, + sharedNHka = bob.third + ) + + val originalText = SecureRandom.getSeed(32); + + val ad = "RatchetsTest".encodeToByteArray().sha256() + var ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + + var plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + + ratchetPayload = ratchets.ratchetEncrypt( + state = bobState, + plaintext = originalText, + ad = ad + ) + + plaintext = ratchets.ratchetDecrypt( + state = aliceState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + } - Cryptography.generateKeysNKServer( - context = context, - authenticationKeypair = bobStaticKeypair, - ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = aliceKeypair.public, - salt = salt, - info = info - ).let { - bobRk = it.first - bobHk = it.second - bobNhk = it.third } - assertArrayEquals(aliceRk, bobRk) - assertArrayEquals(aliceHk, bobHk) - assertArrayEquals(aliceNhk, bobNhk) - } - @Test - fun completeRatchetTest() { - val ratchets = RatchetsHE(context) - val aliceState = States() - ratchets.ratchetInitAlice( - state = aliceState, - sk = aliceRk, - bobDhPublicKey = bobKeypair.public, - sharedHka = aliceHk, - sharedNHka = aliceNhk - ) - - val bobState = States() - ratchets.ratchetInitBob( - state = bobState, - sk = bobRk, - bobKeypair = bobKeypair, - sharedHka = bobHk, - sharedNHka = bobNhk - ) - - val originalText = SecureRandom.getSeed(32); - - val ad = "RatchetsTest".encodeToByteArray().sha256() - var ratchetPayload = ratchets.ratchetEncrypt( - state = aliceState, - plaintext = originalText, - ad = ad - ) - - var plaintext = ratchets.ratchetDecrypt( - state = bobState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - - assertArrayEquals(originalText, plaintext) - - ratchetPayload = ratchets.ratchetEncrypt( - state = bobState, - plaintext = originalText, - ad = ad - ) - - plaintext = ratchets.ratchetDecrypt( - state = aliceState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - - assertArrayEquals(originalText, plaintext) } @Test fun completeRatchetOutOfOrderTest() { - val ratchets = RatchetsHE(context) - val aliceState = States() - ratchets.ratchetInitAlice( - state = aliceState, - sk = aliceRk, - bobDhPublicKey = bobKeypair.public, - sharedHka = aliceHk, - sharedNHka = aliceNhk - ) - - val bobState = States() - ratchets.ratchetInitBob( - state = bobState, - sk = bobRk, - bobKeypair = bobKeypair, - sharedHka = bobHk, - sharedNHka = bobNhk - ) - - val originalText = SecureRandom.getSeed(32); - - val ad = "RatchetsTest".encodeToByteArray().sha256() - var ratchetPayload = ratchets.ratchetEncrypt( - state = aliceState, - plaintext = originalText, - ad = ad - ) - for(i in 1..5) { - ratchetPayload = ratchets.ratchetEncrypt( - state = aliceState, - plaintext = originalText, - ad = ad - ) - } + Cryptography.generateKeysNK( + context = context, + ephemeralKeyPair = aliceKeypair, + authenticationPublicKey = bobStaticKeypair.public, + ephemeralPublicKey = bobKeypair.public, + salt = salt, + info = info + ).use { alice -> + Cryptography.generateKeysNKServer( + context = context, + authenticationKeypair = bobStaticKeypair, + ephemeralKeyPair = bobKeypair, + ephemeralPublicKey = aliceKeypair.public, + salt = salt, + info = info + ).let { bob -> + assertArrayEquals(alice.rk, bob.first) + assertArrayEquals(alice.hk, bob.second) + assertArrayEquals(alice.nhk, bob.third) + + val ratchets = RatchetsHE(context) + val aliceState = States() + ratchets.ratchetInitAlice( + state = aliceState, + sk = alice.rk, + bobDhPublicKey = bobKeypair.public, + sharedHka = alice.hk, + sharedNHka = alice.nhk + ) + + val bobState = States() + ratchets.ratchetInitBob( + state = bobState, + sk = bob.first, + bobKeypair = bobKeypair, + sharedHka = bob.second, + sharedNHka = bob.third + ) + + val originalText = SecureRandom.getSeed(32); + + val ad = "RatchetsTest".encodeToByteArray().sha256() + var ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + + var plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + + ratchetPayload = ratchets.ratchetEncrypt( + state = bobState, + plaintext = originalText, + ad = ad + ) + + plaintext = ratchets.ratchetDecrypt( + state = aliceState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + + for(i in 1..5) { + ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + } + + plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + + ratchetPayload = ratchets.ratchetEncrypt( + state = bobState, + plaintext = originalText, + ad = ad + ) + + plaintext = ratchets.ratchetDecrypt( + state = aliceState, + encHeader = ratchetPayload.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + + assertArrayEquals(originalText, plaintext) + } - var plaintext = ratchets.ratchetDecrypt( - state = bobState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - - assertArrayEquals(originalText, plaintext) - - ratchetPayload = ratchets.ratchetEncrypt( - state = bobState, - plaintext = originalText, - ad = ad - ) - - plaintext = ratchets.ratchetDecrypt( - state = aliceState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - - assertArrayEquals(originalText, plaintext) + } } } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index 504fa0c..e2f5ddd 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -1,6 +1,7 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet import android.content.Context +import androidx.datastore.core.Closeable import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hkdf import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.sha256 import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols @@ -16,6 +17,34 @@ import javax.crypto.spec.SecretKeySpec object Cryptography { + data class NoiseNKKeys( + val rk: ByteArray, + val hk: ByteArray, + val nhk: ByteArray, + ): Closeable { + private var zeroed = false + + override fun close() { + if(!zeroed) { + rk.fill(0) + hk.fill(0) + nhk.fill(0) + zeroed = true + } + } + + inline fun use(block: (NoiseNKKeys) -> T): T { + try { + return block(this) + } finally { + close() + } + } + + // Prevent accidental logging/serialization of key material + override fun toString() = "NoiseNKKeys([REDACTED])" + } + fun generateKeysNK( context: Context, ephemeralKeyPair: AsymmetricCipherKeyPair, @@ -23,7 +52,7 @@ object Cryptography { ephemeralPublicKey: CipherParameters, salt: ByteArray, info: ByteArray, - ): Triple { + ): NoiseNKKeys { val protocols = Protocols(context) val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) @@ -36,7 +65,7 @@ object Cryptography { hkdf1 = hkdf(ikm = dh1, salt = salt, info = info, len = 32) hkdf2 = hkdf(ikm = dh2, salt = hkdf1, info = info, len = 96) - return Triple( + return NoiseNKKeys( hkdf2.sliceArray(0 until 32), hkdf2.sliceArray(32 until 64), hkdf2.sliceArray(64 until 96), @@ -82,10 +111,35 @@ object Cryptography { } } - data class NoiseIKKey( - val keys: Triple, + data class NoiseIKKeys( + val rk: ByteArray, + val hk: ByteArray, + val nhk: ByteArray, val h: ByteArray - ) + ): Closeable { + private var zeroed = false + + override fun close() { + if(!zeroed) { + rk.fill(0) + hk.fill(0) + nhk.fill(0) + h.fill(0) + zeroed = true + } + } + + inline fun use(block: (NoiseIKKeys) -> T): T { + try { + return block(this) + } finally { + close() + } + } + + // Prevent accidental logging/serialization of key material + override fun toString() = "NoiseIKKeys([REDACTED])" + } fun generateKeysIK( context: Context, @@ -94,7 +148,7 @@ object Cryptography { staticKeyPair: AsymmetricCipherKeyPair, info: ByteArray, headerInfo: ByteArray, - ) : NoiseIKKey { + ) : NoiseIKKeys { val protocols = Protocols(context) var h = "Noise_IK_25519_AESGCM_SHA256".encodeToByteArray().sha256() @@ -140,12 +194,10 @@ object Cryptography { hkdf3 = hkdf(ikm = dhSs, salt = ck, info = headerInfo, len = 3) - return NoiseIKKey( - Triple( - hkdf3.sliceArray(0 until 32), - hkdf3.sliceArray(32 until 64), - hkdf3.sliceArray(64 until 96), - ), + return NoiseIKKeys( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), h ) } finally { @@ -172,7 +224,7 @@ object Cryptography { authenticationPublicKey: CipherParameters, info: ByteArray, headerInfo: ByteArray, - ) : NoiseIKKey { + ) : NoiseIKKeys { val protocols = Protocols(context) // Shadowed vars — use local mutable copies so we can zero them @@ -223,12 +275,10 @@ object Cryptography { len = 3 ) - return NoiseIKKey( - Triple( - hkdf3.sliceArray(0 until 32), - hkdf3.sliceArray(32 until 64), - hkdf3.sliceArray(64 until 96), - ), + return NoiseIKKeys( + hkdf3.sliceArray(0 until 32), + hkdf3.sliceArray(32 until 64), + hkdf3.sliceArray(64 until 96), localH ) } finally { diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index 8bcf04d..3390842 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -80,14 +80,19 @@ class RatchetsHE(context: Context) : Protocols(context){ ad: ByteArray, ) : RatchetPayload { val (ck, mk) = kdfCk(state.CKs) - state.CKs = ck - val header = Headers(state.DHRs!!, state.PN, state.Ns) - val encHeader = hEncrypt(state.HKs!!, header.serialized) - state.Ns++ - return RatchetPayload( - header = encHeader, - cipherText = encrypt(mk, plaintext, concat(ad, encHeader)) - ) + try { + state.CKs = ck + val header = Headers(state.DHRs!!, state.PN, state.Ns) + val encHeader = hEncrypt(state.HKs!!, header.serialized) + state.Ns++ + return RatchetPayload( + header = encHeader, + cipherText = encrypt(mk, plaintext, concat(ad, encHeader)) + ) + } finally { + ck.fill(0) + mk.fill(0) + } } fun ratchetDecrypt( @@ -107,11 +112,16 @@ class RatchetsHE(context: Context) : Protocols(context){ } skipMessageKeys(state, header.n.toInt()) - val kdfCk = kdfCk(state.CKr) - state.CKr = kdfCk.first - val mk = kdfCk.second - state.Nr++ - return decrypt(mk, cipherText, concat(ad, encHeader)) + + val (ck, mk) = kdfCk(state.CKr) + try { + state.CKr = ck + state.Nr++ + return decrypt(mk, cipherText, concat(ad, encHeader)) + } finally { + ck.fill(0) + mk.fill(0) + } } private fun skipMessageKeys( @@ -123,11 +133,16 @@ class RatchetsHE(context: Context) : Protocols(context){ state.CKr?.let{ while(state.Nr.toInt() < until) { - val kdfCk = kdfCk(state.CKr) - state.CKr = kdfCk.first - val mk = kdfCk.second - state.MKSKIPPED[Pair(state.HKr, state.Nr.toInt())] = mk - state.Nr++ + val (ck, mk) = kdfCk(state.CKr) + try { + state.CKr = ck + val mk = mk + state.MKSKIPPED[Pair(state.HKr, state.Nr.toInt())] = mk + state.Nr++ + } finally { + ck.fill(0) + mk.fill(0) + } } } } @@ -142,12 +157,17 @@ class RatchetsHE(context: Context) : Protocols(context){ val (hk, n) = it.key val mk = it.value - val header = hDecrypt(hk, encHeader).run { - Headers.deserialize(this) - } - if(header.n.toInt() == n) { - state.MKSKIPPED.remove(it.key) - return decrypt(mk, ciphertext, concat(ad, encHeader)) + try { + val header = hDecrypt(hk, encHeader).run { + Headers.deserialize(this) + } + if(header.n.toInt() == n) { + state.MKSKIPPED.remove(it.key) + return decrypt(mk, ciphertext, concat(ad, encHeader)) + } + } finally { + hk.fill(0) + mk.fill(0) } } @@ -186,28 +206,38 @@ class RatchetsHE(context: Context) : Protocols(context){ state.HKr = state.NHKr state.DHRr = header.dh.public - kdfRk(state.RK!!, + val (rk, ck, nhk) = kdfRk(state.RK!!, dh( state.DHRs!!, state.DHRr!!, ) - ).let { - state.RK = it.first - state.CKr = it.second - state.NHKr = it.third + ) + try { + state.RK = rk.copyOf() + state.CKr = ck.copyOf() + state.NHKr = nhk.copyOf() + } finally { + rk.fill(0) + ck.fill(0) + nhk.fill(0) } state.DHRs = generateDH() - kdfRk(state.RK!!, + val (rk1, ck1, nhk1) = kdfRk(state.RK!!, dh( state.DHRs!!, state.DHRr!!, ) - ).let { - state.RK = it.first - state.CKs = it.second - state.NHKs = it.third + ) + try { + state.RK = rk1.copyOf() + state.CKs = ck1.copyOf() + state.NHKs = nhk1.copyOf() + } finally { + rk1.fill(0) + ck1.fill(0) + nhk1.fill(0) } } } \ No newline at end of file From 439872d3b45f1299e800866d3521d9b1281548cf Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 14 Apr 2026 14:59:32 +0100 Subject: [PATCH 13/19] update: memory for noise ik --- .../libsignal_doubleratchet/Cryptography.kt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index e2f5ddd..b5c33aa 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -115,7 +115,8 @@ object Cryptography { val rk: ByteArray, val hk: ByteArray, val nhk: ByteArray, - val h: ByteArray + val ck: ByteArray? = null, + val h: ByteArray? = null, ): Closeable { private var zeroed = false @@ -124,7 +125,8 @@ object Cryptography { rk.fill(0) hk.fill(0) nhk.fill(0) - h.fill(0) + ck?.fill(0) + h?.fill(0) zeroed = true } } @@ -198,6 +200,7 @@ object Cryptography { hkdf3.sliceArray(0 until 32), hkdf3.sliceArray(32 until 64), hkdf3.sliceArray(64 until 96), + ck, h ) } finally { @@ -279,7 +282,6 @@ object Cryptography { hkdf3.sliceArray(0 until 32), hkdf3.sliceArray(32 until 64), hkdf3.sliceArray(64 until 96), - localH ) } finally { dhEe.fill(0) From a42dea9702c39d69868ee9fab5a5827e36aa6b3a Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 21 Apr 2026 12:09:02 +0100 Subject: [PATCH 14/19] update: refactored --- .../SecurityAESTest.kt | 23 ----- .../SecurityRSATest.java | 54 ----------- .../SecurityX25519Test.kt | 66 ------------- .../libsignal/RatchetsTest.kt | 22 ++--- .../libsignal_doubleratchet/Cryptography.kt | 35 ++++--- .../libsignal_doubleratchet/SecurityAES.java | 91 ------------------ .../libsignal_doubleratchet/SecurityRSA.kt | 90 ------------------ .../extensions/context.kt | 94 ------------------- .../libsignal/Headers.kt | 9 +- .../libsignal/Protocols.kt | 83 +++++++++++++--- .../libsignal/RatchetsHE.kt | 12 +-- .../libsignal/States.kt | 58 ++++++++++-- 12 files changed, 159 insertions(+), 478 deletions(-) delete mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt delete mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java delete mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt delete mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java delete mode 100644 double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt deleted file mode 100644 index 5b92d58..0000000 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAESTest.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.content.Context -import androidx.test.espresso.internal.inject.InstrumentationContext -import androidx.test.filters.SmallTest -import androidx.test.platform.app.InstrumentationRegistry -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.extensions.generateRandomBytes -import org.junit.Assert.assertArrayEquals -import org.junit.Test - -@SmallTest -class SecurityAESTest { - var context: Context = InstrumentationRegistry.getInstrumentation().targetContext - @Test - fun aesTest() { - val secretKey = SecurityAES.generateSecretKey(256) - val input = context.generateRandomBytes(277) - val cipher = SecurityAES.encryptAES256CBC(input, secretKey.encoded, null) - val output = SecurityAES.decryptAES256CBC(cipher, secretKey.encoded, null) - - assertArrayEquals(input, output) - } -} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java deleted file mode 100644 index 98487f6..0000000 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSATest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet; - - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import androidx.test.ext.junit.runners.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.UnrecoverableEntryException; -import java.security.cert.CertificateException; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -@RunWith(AndroidJUnit4.class) -public class SecurityRSATest { - - String keystoreAlias = "keystoreAlias"; - @Test - public void testCanStoreAndEncrypt() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnrecoverableEntryException, CertificateException, KeyStoreException, IOException { -// KeyPairGenerator kpg = KeyPairGenerator.getInstance( -// KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); -// -// kpg.initialize(new KeyGenParameterSpec.Builder(keystoreAlias, -// KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) -// .setKeySize(2048) -// .setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, -// KeyProperties.DIGEST_SHA512) -// .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) -// .build()); -// -// KeyPair keyPair = kpg.generateKeyPair(); -// PublicKey publicKey = SecurityRSA.generateKeyPair(keystoreAlias, 2048); -// KeyPair keyPair = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias); -// -// SecretKey secretKey = SecurityAES.generateSecretKey(256); -// byte[] cipherText = SecurityRSA.encrypt(keyPair.getPublic(), secretKey.getEncoded()); -// byte[] plainText = SecurityRSA.decrypt(keyPair.getPrivate(), cipherText); -// assertArrayEquals(secretKey.getEncoded(), plainText); - } -} diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt deleted file mode 100644 index 545634d..0000000 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityX25519Test.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.content.Context -import android.security.keystore.KeyGenParameterSpec -import android.security.keystore.KeyProperties -import androidx.test.filters.SmallTest -import androidx.test.platform.app.InstrumentationRegistry -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Protocols -import org.junit.Assert.assertArrayEquals -import org.junit.Test -import java.security.KeyPairGenerator -import java.security.KeyStore -import java.security.Signature - -@SmallTest -class SecurityX25519Test { - - var context: Context = InstrumentationRegistry.getInstrumentation().targetContext - - @Test - fun keystoreEd25519() { - val keystoreAlias = "keystoreAlias" - val kpg: KeyPairGenerator = KeyPairGenerator.getInstance( - KeyProperties.KEY_ALGORITHM_EC, - "AndroidKeyStore" - ) - val parameterSpec: KeyGenParameterSpec = KeyGenParameterSpec.Builder( - keystoreAlias, - KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY - ).run { - setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) - build() - } - - kpg.initialize(parameterSpec) - val kp = kpg.generateKeyPair() - - val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { - load(null) - } - val entry: KeyStore.Entry = ks.getEntry(keystoreAlias, null) - if (entry !is KeyStore.PrivateKeyEntry) { - throw Exception("No instance of keystore") - } - - val data = "Hello world".encodeToByteArray() - val signature: ByteArray = Signature.getInstance("SHA256withECDSA").run { - initSign(entry.privateKey) - update(data) - sign() - } - - } - - @Test - fun sharedSecret() { - val protocols = Protocols(context) - val alice = protocols.generateDH() - val bob = protocols.generateDH() - - val aliceSharedSecret = protocols.dh(alice, bob.public) - val bobSharedSecret = protocols.dh(bob, alice.public) - - assertArrayEquals(aliceSharedSecret, bobSharedSecret) - } -} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index 35b03d7..c1a5ba0 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -25,17 +25,17 @@ class RatchetsTest { val salt = "completeRatchetTest_v1".encodeToByteArray() val info = context.generateRandomBytes(16) + - (aliceKeypair.public as X25519PublicKeyParameters).encoded + - (bobKeypair.public as X25519PublicKeyParameters).encoded + - (bobStaticKeypair.public as X25519PublicKeyParameters).encoded + aliceKeypair.publicKey + + bobKeypair.publicKey + + bobStaticKeypair.publicKey @Test fun completeRatchetTest() { Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, - authenticationPublicKey = bobStaticKeypair.public, - ephemeralPublicKey = bobKeypair.public, + authenticationPublicKey = X25519PublicKeyParameters(bobStaticKeypair.publicKey), + ephemeralPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), salt = salt, info = info ).use { alice -> @@ -43,7 +43,7 @@ class RatchetsTest { context = context, authenticationKeypair = bobStaticKeypair, ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = aliceKeypair.public, + ephemeralPublicKey = X25519PublicKeyParameters(aliceKeypair.publicKey), salt = salt, info = info ).let { bob -> @@ -56,7 +56,7 @@ class RatchetsTest { ratchets.ratchetInitAlice( state = aliceState, sk = alice.rk, - bobDhPublicKey = bobKeypair.public, + bobDhPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), sharedHka = alice.hk, sharedNHka = alice.nhk ) @@ -114,8 +114,8 @@ class RatchetsTest { Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, - authenticationPublicKey = bobStaticKeypair.public, - ephemeralPublicKey = bobKeypair.public, + authenticationPublicKey = X25519PublicKeyParameters(bobStaticKeypair.publicKey), + ephemeralPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), salt = salt, info = info ).use { alice -> @@ -123,7 +123,7 @@ class RatchetsTest { context = context, authenticationKeypair = bobStaticKeypair, ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = aliceKeypair.public, + ephemeralPublicKey = X25519PublicKeyParameters(aliceKeypair.publicKey), salt = salt, info = info ).let { bob -> @@ -136,7 +136,7 @@ class RatchetsTest { ratchets.ratchetInitAlice( state = aliceState, sk = alice.rk, - bobDhPublicKey = bobKeypair.public, + bobDhPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), sharedHka = alice.hk, sharedNHka = alice.nhk ) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index b5c33aa..7dae0cf 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -47,7 +47,7 @@ object Cryptography { fun generateKeysNK( context: Context, - ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, authenticationPublicKey: CipherParameters, ephemeralPublicKey: CipherParameters, salt: ByteArray, @@ -81,8 +81,8 @@ object Cryptography { } fun generateKeysNKServer( context: Context, - authenticationKeypair: AsymmetricCipherKeyPair, - ephemeralKeyPair: AsymmetricCipherKeyPair, + authenticationKeypair: Protocols.CloseableCurve15519KeyPair, + ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, ephemeralPublicKey: CipherParameters, salt: ByteArray, info: ByteArray, @@ -145,9 +145,9 @@ object Cryptography { fun generateKeysIK( context: Context, - ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, authenticationPublicKey: CipherParameters, - staticKeyPair: AsymmetricCipherKeyPair, + staticKeyPair: Protocols.CloseableCurve15519KeyPair, info: ByteArray, headerInfo: ByteArray, ) : NoiseIKKeys { @@ -157,7 +157,7 @@ object Cryptography { var ck = h h = (h + (authenticationPublicKey as X25519PublicKeyParameters).encoded).sha256() - h = (h + (ephemeralKeyPair.public as X25519PublicKeyParameters).encoded).sha256() + h = (h + ephemeralKeyPair.publicKey).sha256() val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) @@ -175,9 +175,9 @@ object Cryptography { ck = hkdf1.sliceArray(0 until 32) k = hkdf1.sliceArray(32 until 64) - csPkEnc = Cryptography.AesGcm.encrypt( + csPkEnc = AesGcm.encrypt( SecretKeySpec(k, "AES"), - (staticKeyPair.public as X25519PublicKeyParameters).encoded, + staticKeyPair.publicKey, h ) h = (h + csPkEnc).sha256() @@ -222,7 +222,7 @@ object Cryptography { context: Context, h: ByteArray, ck: ByteArray, - ephemeralKeyPair: AsymmetricCipherKeyPair, + ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, ephemeralResponderPublicKey: CipherParameters, authenticationPublicKey: CipherParameters, info: ByteArray, @@ -251,7 +251,7 @@ object Cryptography { localCk = hkdf1.sliceArray(0 until 32) k = hkdf1.sliceArray(32 until 64) - ciphertext1 = Cryptography.AesGcm.encrypt( + ciphertext1 = AesGcm.encrypt( SecretKeySpec(k, "AES"), "".encodeToByteArray(), localH @@ -264,7 +264,7 @@ object Cryptography { k.fill(0) // zero previous k before reassign k = hkdf2.sliceArray(32 until 64) - ciphertext2 = Cryptography.AesGcm.encrypt( + ciphertext2 = AesGcm.encrypt( SecretKeySpec(k, "AES"), "".encodeToByteArray(), localH @@ -282,6 +282,7 @@ object Cryptography { hkdf3.sliceArray(0 until 32), hkdf3.sliceArray(32 until 64), hkdf3.sliceArray(64 until 96), + h = localH ) } finally { dhEe.fill(0) @@ -309,11 +310,6 @@ object Cryptography { val iv: ByteArray // IV — must be stored alongside ciphertext for decryption ) - fun generateKey(): SecretKey { - val keygen = KeyGenerator.getInstance("AES") - keygen.init(KEY_SIZE_BITS, SecureRandom()) - return keygen.generateKey() - } /** * Encrypts [plaintext] with AES-256-GCM. @@ -327,17 +323,18 @@ object Cryptography { fun encrypt( key: SecretKey, plaintext: ByteArray, + iv: ByteArray? = null, associatedData: ByteArray? = null ): ByteArray { - val iv = ByteArray(IV_SIZE_BYTES).also { SecureRandom().nextBytes(it) } - val spec = GCMParameterSpec(TAG_SIZE_BITS, iv) + val iv1 = iv ?: ByteArray(IV_SIZE_BYTES).also { SecureRandom().nextBytes(it) } + val spec = GCMParameterSpec(TAG_SIZE_BITS, iv1) val cipher = Cipher.getInstance(ALGORITHM) cipher.init(Cipher.ENCRYPT_MODE, key, spec) associatedData?.let { cipher.updateAAD(it) } val ciphertext = cipher.doFinal(plaintext) - return iv + ciphertext + return if(iv != null) ciphertext else iv1 + ciphertext } /** diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java deleted file mode 100644 index 30e47a1..0000000 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityAES.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet; - -import android.security.keystore.KeyProperties; - -import com.google.common.primitives.Bytes; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.KeyGenerator; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -public class SecurityAES { - - public static final String DEFAULT_AES_ALGORITHM = "AES/CBC/PKCS5Padding"; - - public static final String ALGORITHM = "AES"; - - public static SecretKey generateSecretKey(int size) throws NoSuchAlgorithmException { - KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES); - keyGenerator.init(size); // Adjust key size as needed - return keyGenerator.generateKey(); - } - - public static byte[] encryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); - aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); - byte[] cipherText = aesCipher.doFinal(data); - - final byte[] IV = aesCipher.getIV(); - byte[] cipherTextIv = new byte[IV.length + cipherText.length]; - System.arraycopy(IV, 0, cipherTextIv, 0, IV.length); - System.arraycopy(cipherText, 0, cipherTextIv, IV.length, cipherText.length); - return cipherTextIv; - } - - public static byte[] decryptAESGCM(byte[] data, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { - byte[] iv = new byte[12]; - System.arraycopy(data, 0, iv, 0, iv.length); - - byte[] _data = new byte[data.length - iv.length]; - System.arraycopy(data, iv.length, _data, 0, _data.length); - - GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128,iv); - - Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); - aesCipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec); - return aesCipher.doFinal(_data); - } - - public static byte[] encryptAES256CBC(byte[] input, byte[] secretKey, byte[] iv) throws Throwable { - SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, 0, secretKey.length, "AES"); - - Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); - if(iv != null) { - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(input); - } - - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] ciphertext = cipher.doFinal(input); - return Bytes.concat(cipher.getIV(), ciphertext); - } - - public static byte[] decryptAES256CBC(byte[] input, byte[] sharedKey, byte[] iv) throws Throwable { - SecretKeySpec secretKeySpec = new SecretKeySpec(sharedKey, ALGORITHM); - - Cipher cipher = Cipher.getInstance(DEFAULT_AES_ALGORITHM); - if(iv == null) { - iv = new byte[16]; - System.arraycopy(input, 0, iv, 0, 16); - - byte[] content = new byte[input.length - 16]; - System.arraycopy(input, 16, content, 0, content.length); - input = content; - } - - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(input); - } -} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt deleted file mode 100644 index fa8112d..0000000 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/SecurityRSA.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.afkanerd.smswithoutborders.libsignal_doubleratchet - -import android.security.keystore.KeyGenParameterSpec -import android.security.keystore.KeyProperties -import java.security.InvalidAlgorithmParameterException -import java.security.InvalidKeyException -import java.security.KeyPairGenerator -import java.security.NoSuchAlgorithmException -import java.security.NoSuchProviderException -import java.security.PrivateKey -import java.security.PublicKey -import java.security.spec.MGF1ParameterSpec -import javax.crypto.BadPaddingException -import javax.crypto.Cipher -import javax.crypto.IllegalBlockSizeException -import javax.crypto.NoSuchPaddingException -import javax.crypto.spec.OAEPParameterSpec -import javax.crypto.spec.PSource - -object SecurityRSA { - var defaultEncryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA256 - var defaultDecryptionDigest: MGF1ParameterSpec? = MGF1ParameterSpec.SHA1 - - var encryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( - "SHA-256", "MGF1", defaultEncryptionDigest, - PSource.PSpecified.DEFAULT - ) - var decryptionDigestParam: OAEPParameterSpec = OAEPParameterSpec( - "SHA-256", "MGF1", defaultDecryptionDigest, - PSource.PSpecified.DEFAULT - ) - - @JvmStatic - @Throws( - NoSuchAlgorithmException::class, - NoSuchProviderException::class, - InvalidAlgorithmParameterException::class - ) - fun generateKeyPair(keystoreAlias: String, keySize: Int = 2048): PublicKey? { - val kpg = KeyPairGenerator.getInstance( - KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore" - ) - kpg.initialize( - KeyGenParameterSpec.Builder( - keystoreAlias, - KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT - ) - .setKeySize(keySize) - .setDigests( - KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256, - KeyProperties.DIGEST_SHA512 - ) - .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - .build() - ) - return kpg.generateKeyPair().public - } - - @JvmStatic - @Throws( - NoSuchPaddingException::class, - NoSuchAlgorithmException::class, - IllegalBlockSizeException::class, - BadPaddingException::class, - InvalidKeyException::class, - InvalidAlgorithmParameterException::class - ) - fun decrypt(privateKey: PrivateKey?, data: ByteArray?): ByteArray? { - val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - // cipher.init(Cipher.DECRYPT_MODE, privateKey, decryptionDigestParam); - cipher.init(Cipher.DECRYPT_MODE, privateKey) - return cipher.doFinal(data) - } - - @JvmStatic - @Throws( - NoSuchPaddingException::class, - NoSuchAlgorithmException::class, - IllegalBlockSizeException::class, - BadPaddingException::class, - InvalidKeyException::class, - InvalidAlgorithmParameterException::class - ) - fun encrypt(publicKey: PublicKey?, data: ByteArray?): ByteArray? { - val cipher = Cipher.getInstance("RSA/ECB/" + KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) - // cipher.init(Cipher.ENCRYPT_MODE, publicKey, encryptionDigestParam); - cipher.init(Cipher.ENCRYPT_MODE, publicKey) - return cipher.doFinal(data) - } -} diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt index 9cafd07..27c1a10 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/extensions/context.kt @@ -8,8 +8,6 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityRSA import com.google.gson.Gson import kotlinx.coroutines.flow.first import java.io.IOException @@ -25,45 +23,6 @@ import javax.crypto.spec.SecretKeySpec val Context.dataStore: DataStore by preferencesDataStore(name = "secure_comms") -/** - * Pair - */ -suspend fun Context.getKeypairValues(address: String): Pair { - val keyValue = stringSetPreferencesKey(address + "_keypair") - val keypairSet = dataStore.data.first()[keyValue] - val encryptionPublicKey = getKeypairFromKeystore(address) - - val publicKey = SecurityRSA.decrypt( - encryptionPublicKey?.private, - Base64.decode(keypairSet?.elementAt(0), Base64.DEFAULT) - ) - val privateKey = SecurityRSA.decrypt( - encryptionPublicKey?.private, - Base64.decode(keypairSet?.elementAt(1), Base64.DEFAULT) - ) - return Pair(publicKey, privateKey) -} - -suspend fun Context.setKeypairValues( - address: String, - publicKey: ByteArray, - privateKey: ByteArray, -) { - val encryptionPublicKey = SecurityRSA.generateKeyPair(address) - - val keyValue = stringSetPreferencesKey(address + "_keypair") - dataStore.edit { secureComms-> - secureComms[keyValue] = setOf( - Base64.encodeToString(publicKey.run { - SecurityRSA.encrypt(encryptionPublicKey, this) - }, Base64.DEFAULT), - Base64.encodeToString(privateKey.run { - SecurityRSA.encrypt(encryptionPublicKey, this) - }, Base64.DEFAULT), - ) - } -} - @Throws( KeyStoreException::class, CertificateException::class, @@ -93,59 +52,6 @@ data class SavedBinaryData( /** * Would overwrite anything with the same Keystore Alias */ -@Throws -suspend fun Context.saveBinaryDataEncrypted( - keystoreAlias: String, - data: ByteArray, -) : Boolean { - val keyValue = stringPreferencesKey(keystoreAlias) - - val aesGcmKey = SecurityAES.generateSecretKey(256) - val data = SecurityAES.encryptAESGCM(data, aesGcmKey) - -// val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias)?.public -// ?: SecurityRSA.generateKeyPair(keystoreAlias) - - var saved = false - dataStore.edit { secureComms-> - try { - val encryptionPublicKey = SecurityRSA.generateKeyPair(keystoreAlias) - SecurityRSA.encrypt(encryptionPublicKey, aesGcmKey.encoded)?.let { key -> - secureComms[keyValue] = Gson().toJson( - SavedBinaryData( - key = key, - algorithm = aesGcmKey.algorithm, - data = data - ) - ) - saved = true - } - } catch(e: Exception) { - throw e - } - } - return saved -} - -@Throws -suspend fun Context.getEncryptedBinaryData(keystoreAlias: String): ByteArray? { - val keyValue = stringPreferencesKey(keystoreAlias) - val data = dataStore.data.first()[keyValue] ?: return null - - val savedBinaryData = Gson().fromJson(data, SavedBinaryData::class.java) - - return try { - val encryptionPublicKey = getKeypairFromKeystore(keystoreAlias) - SecurityRSA.decrypt(encryptionPublicKey?.private, savedBinaryData.key) - ?.run { - SecurityAES.decryptAESGCM(savedBinaryData.data, - SecretKeySpec(this, savedBinaryData.algorithm) - ) - } - } catch(e: Exception) { - throw e - } -} fun Context.generateRandomBytes(length: Int): ByteArray { val random = SecureRandom() diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt index f37fde8..1dbc230 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Headers.kt @@ -7,7 +7,7 @@ import java.nio.ByteBuffer import java.nio.ByteOrder import java.security.KeyPair -class Headers(var dh: AsymmetricCipherKeyPair, pn: UByte, n: UByte) { +class Headers(var dh: Protocols.CloseableCurve15519KeyPair, pn: UByte, n: UByte) { var pn: UByte = 0u var n: UByte = 0u @@ -18,8 +18,7 @@ class Headers(var dh: AsymmetricCipherKeyPair, pn: UByte, n: UByte) { val serialized: ByteArray get() { - val pk = dh.public as X25519PublicKeyParameters - return byteArrayOf(pn.toByte()) + byteArrayOf(n.toByte()) + pk.encoded + return byteArrayOf(pn.toByte()) + byteArrayOf(n.toByte()) + dh.publicKey } companion object { @@ -28,8 +27,8 @@ class Headers(var dh: AsymmetricCipherKeyPair, pn: UByte, n: UByte) { val n = header[1].toUByte() val pk = header.sliceArray(2 until header.size) return Headers( - AsymmetricCipherKeyPair( - X25519PublicKeyParameters(pk, 0), + Protocols.CloseableCurve15519KeyPair( + pk, null ), pn, n) } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 8ff979d..65c12b9 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -5,22 +5,28 @@ import android.util.Pair import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hkdf import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hmac +import com.afkanerd.smswithoutborders.libsignal_doubleratchet.Cryptography import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R -import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES import com.google.common.primitives.Bytes import org.bouncycastle.crypto.AsymmetricCipherKeyPair import org.bouncycastle.crypto.CipherParameters import org.bouncycastle.crypto.agreement.X25519Agreement import org.bouncycastle.crypto.generators.X25519KeyPairGenerator import org.bouncycastle.crypto.params.X25519KeyGenerationParameters +import org.bouncycastle.crypto.params.X25519PrivateKeyParameters +import org.bouncycastle.crypto.params.X25519PublicKeyParameters import org.bouncycastle.jce.provider.BouncyCastleProvider +import java.lang.AutoCloseable +import java.security.PrivateKey import java.security.SecureRandom import java.security.Security +import javax.crypto.SecretKey +import javax.crypto.spec.SecretKeySpec /** - * This implementations are based on the signal protocols specifications. + * These implementations are based on the signal protocols specifications. * - * This are based on the recommended algorithms and parameters for the encryption + * These are based on the recommended algorithms and parameters for the encryption * and decryption. * * The goal for this would be to transform it into library which can be used across @@ -37,17 +43,50 @@ open class Protocols(private val context: Context) { Security.addProvider(BouncyCastleProvider()) } - fun generateDH(): AsymmetricCipherKeyPair { + data class CloseableCurve15519KeyPair( + var publicKey: ByteArray, + var privateKey: ByteArray? + ): AutoCloseable { + private var isClosed = false + + fun use(block: (CloseableCurve15519KeyPair) -> Unit) { + if (isClosed) throw IllegalStateException("Cannot use zeroed RatchetState") + block(this) + } + + override fun close() { + if(isClosed) return + publicKey.fill(0) + privateKey?.fill(0) + isClosed = true + } + + } + + fun generateDH(): CloseableCurve15519KeyPair { val generator = X25519KeyPairGenerator() generator.init(X25519KeyGenerationParameters(SecureRandom())) - return generator.generateKeyPair() + + val keypair = generator.generateKeyPair() + return try { + CloseableCurve15519KeyPair( + publicKey = (keypair.public as X25519PublicKeyParameters).encoded, + privateKey = (keypair.private as X25519PrivateKeyParameters).encoded, + ) + } catch(e: Exception) { + e.printStackTrace() + (keypair.private as? X25519PrivateKeyParameters)?.encoded?.fill(0) + throw e + } } - fun dh(keypair: AsymmetricCipherKeyPair, publicKey: CipherParameters): ByteArray { + fun dh(keypair: CloseableCurve15519KeyPair, publicKey: CipherParameters): ByteArray { val sharedSecret = ByteArray(32) val agreement = X25519Agreement() - agreement.init(keypair.private) - agreement.calculateAgreement(publicKey, sharedSecret, 0) + keypair.use { kp -> + agreement.init(X25519PrivateKeyParameters(kp.privateKey, 0)) + agreement.calculateAgreement(publicKey, sharedSecret, 0) + } return sharedSecret } @@ -90,7 +129,11 @@ open class Protocols(private val context: Context) { val authKey = this.sliceArray(32 until 64) val iv = this.sliceArray(64 until 80) - val cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv) + val cipherText = Cryptography.AesGcm.encrypt( + key = SecretKeySpec(key, "AES"), + iv = iv, + plaintext = plainText, + ) val mac = hmac(authKey) mac.update(ad + cipherText) cipherText + mac.doFinal() @@ -112,7 +155,11 @@ open class Protocols(private val context: Context) { val authKey = this.sliceArray(32 until 64) val iv = this.sliceArray(64 until 80) - val cipherText = SecurityAES.encryptAES256CBC(plainText, key, iv) + val cipherText = Cryptography.AesGcm.encrypt( + key = SecretKeySpec(key, "AES"), + iv = iv, + plaintext = plainText, + ) val mac = hmac(authKey) mac.update(cipherText) @@ -141,12 +188,18 @@ open class Protocols(private val context: Context) { val key = this.sliceArray(0 until 32) val iv = this.sliceArray(64 until 80) - SecurityAES.decryptAES256CBC(plaintextCiphertext, key, iv) + Cryptography.AesGcm.decrypt( + key = SecretKeySpec(key, "AES"), + ciphertext = plaintextCiphertext, + iv = iv, + ) } } - fun hDecrypt(mk: ByteArray, cipherText: ByteArray): ByteArray { + fun hDecrypt(mk: ByteArray?, cipherText: ByteArray): ByteArray? { val len = 80 + if(mk == null) return null + return hkdf( ikm = mk, salt = ByteArray(len), @@ -166,7 +219,11 @@ open class Protocols(private val context: Context) { val key = this.sliceArray(0 until 32) val iv = this.sliceArray(64 until 80) - SecurityAES.decryptAES256CBC(plainCiphertext, key, iv) + Cryptography.AesGcm.decrypt( + key = SecretKeySpec(key, "AES"), + ciphertext = plainCiphertext, + iv = iv, + ) } } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index 3390842..4b2606c 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -55,7 +55,7 @@ class RatchetsHE(context: Context) : Protocols(context){ fun ratchetInitBob( state: States, sk: ByteArray, - bobKeypair: AsymmetricCipherKeyPair, + bobKeypair: CloseableCurve15519KeyPair, sharedHka: ByteArray, sharedNHka: ByteArray, ) { @@ -158,10 +158,10 @@ class RatchetsHE(context: Context) : Protocols(context){ val mk = it.value try { - val header = hDecrypt(hk, encHeader).run { + val header = hDecrypt(hk, encHeader)?.run { Headers.deserialize(this) } - if(header.n.toInt() == n) { + if(header != null && header.n.toInt() == n) { state.MKSKIPPED.remove(it.key) return decrypt(mk, ciphertext, concat(ad, encHeader)) } @@ -180,7 +180,7 @@ class RatchetsHE(context: Context) : Protocols(context){ ) : Pair { var header: Headers? = null try { - header = hDecrypt(state.HKr!!, encHeader).run { + header = hDecrypt(state.HKr, encHeader)?.run { Headers.deserialize(this) } } catch(e: Exception) { @@ -191,7 +191,7 @@ class RatchetsHE(context: Context) : Protocols(context){ return Pair(header, false) } - header = hDecrypt(state.NHKr!!, encHeader).run { + header = hDecrypt(state.NHKr!!, encHeader)?.run { Headers.deserialize(this) } @@ -204,7 +204,7 @@ class RatchetsHE(context: Context) : Protocols(context){ state.Nr = 0u state.HKs = state.NHKs state.HKr = state.NHKr - state.DHRr = header.dh.public + state.DHRr = X25519PublicKeyParameters(header.dh.publicKey) val (rk, ck, nhk) = kdfRk(state.RK!!, dh( diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt index fe0b438..f3d6810 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -1,10 +1,18 @@ package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal +import android.R.id.input import android.util.Pair +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import kotlinx.serialization.json.decodeFromStream +import kotlinx.serialization.json.encodeToStream import org.bouncycastle.crypto.AsymmetricCipherKeyPair import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters +import java.io.ByteArrayOutputStream +import java.lang.AutoCloseable import java.security.KeyPair import java.security.PrivateKey import java.security.PublicKey @@ -17,21 +25,59 @@ data class States( var Ns: UByte = 0u, var Nr: UByte = 0u, var PN: UByte = 0u, - var DHRs: AsymmetricCipherKeyPair? = null, + var DHRs: Protocols.CloseableCurve15519KeyPair? = null, var DHRr: CipherParameters? = null, var HKs: ByteArray? = null, var HKr: ByteArray? = null, var NHKs: ByteArray? = null, var NHKr: ByteArray? = null, var MKSKIPPED: MutableMap, ByteArray> = mutableMapOf() -) { - fun serialize(): String { - return Json.encodeToString(this) +) : AutoCloseable { + @OptIn(ExperimentalSerializationApi::class) + fun serialize(): ByteArray { + val outputBuffer = ByteArrayOutputStream() + Json.encodeToStream(this, outputBuffer) + return outputBuffer.toByteArray() + } + + private var isClosed = false + override fun close() { + if(isClosed) return + RK?.let { it.fill(0); RK = null } + CKs?.let { it.fill(0); CKs = null } + CKr?.let { it.fill(0); CKr = null } + HKs?.let { it.fill(0); HKs = null } + HKr?.let { it.fill(0); HKr = null } + NHKs?.let { it.fill(0); NHKs = null } + NHKr?.let { it.fill(0); NHKr = null } + + (DHRr as? Ed25519PublicKeyParameters)?.encoded?.fill(0) + DHRr = null + + val iterator = MKSKIPPED.entries.iterator() + while (iterator.hasNext()) { + val entry = iterator.next() + entry.key.first.fill(0) + entry.value.fill(0) + iterator.remove() + } + MKSKIPPED.clear() + + Ns = 0u + Nr = 0u + PN = 0u + isClosed = true + } + + fun use(block: (States) -> Unit) { + if (isClosed) throw IllegalStateException("Cannot use zeroed RatchetState") + block(this) } companion object { - fun deserialize(input: String): States { - return Json.decodeFromString(input) + @OptIn(ExperimentalSerializationApi::class) + fun deserialize(data: ByteArray): States { + return Json.decodeFromStream(data.inputStream()) } } } \ No newline at end of file From dfc9711fcba056f4372f692f65fef2935c172f86 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Tue, 21 Apr 2026 19:21:46 +0100 Subject: [PATCH 15/19] update: bytes are easier to zero out --- .../libsignal/PoCTest.kt | 28 +++++++++++++++++++ .../libsignal/RatchetsTest.kt | 16 +++++------ .../libsignal_doubleratchet/Cryptography.kt | 14 +++++----- .../libsignal/Protocols.kt | 10 +++++-- .../libsignal/RatchetsHE.kt | 4 +-- .../libsignal/States.kt | 5 ++-- 6 files changed, 54 insertions(+), 23 deletions(-) create mode 100644 double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/PoCTest.kt diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/PoCTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/PoCTest.kt new file mode 100644 index 0000000..ba88ab8 --- /dev/null +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/PoCTest.kt @@ -0,0 +1,28 @@ +package com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal + +import android.content.Context +import androidx.test.filters.SmallTest +import androidx.test.platform.app.InstrumentationRegistry +import org.bouncycastle.crypto.CipherParameters +import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters +import org.bouncycastle.crypto.params.X25519PublicKeyParameters +import org.junit.Assert.assertArrayEquals +import org.junit.Test + +@SmallTest +class PoCTest { + + var context: Context = + InstrumentationRegistry.getInstrumentation().targetContext + val protocol = Protocols(context) + + @Test + fun zeroing() { + val keypair = protocol.generateDH() + val publicKey = X25519PublicKeyParameters(keypair.publicKey) + + publicKey.encoded.fill(0) + val expected = ByteArray(32) + assertArrayEquals(expected, publicKey.encoded) + } +} \ No newline at end of file diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index c1a5ba0..52506c3 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -34,8 +34,8 @@ class RatchetsTest { Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, - authenticationPublicKey = X25519PublicKeyParameters(bobStaticKeypair.publicKey), - ephemeralPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), + authenticationPublicKey = bobStaticKeypair.publicKey, + ephemeralPublicKey = bobKeypair.publicKey, salt = salt, info = info ).use { alice -> @@ -43,7 +43,7 @@ class RatchetsTest { context = context, authenticationKeypair = bobStaticKeypair, ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = X25519PublicKeyParameters(aliceKeypair.publicKey), + ephemeralPublicKey = aliceKeypair.publicKey, salt = salt, info = info ).let { bob -> @@ -56,7 +56,7 @@ class RatchetsTest { ratchets.ratchetInitAlice( state = aliceState, sk = alice.rk, - bobDhPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), + bobDhPublicKey = bobKeypair.publicKey, sharedHka = alice.hk, sharedNHka = alice.nhk ) @@ -114,8 +114,8 @@ class RatchetsTest { Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, - authenticationPublicKey = X25519PublicKeyParameters(bobStaticKeypair.publicKey), - ephemeralPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), + authenticationPublicKey = bobStaticKeypair.publicKey, + ephemeralPublicKey = bobKeypair.publicKey, salt = salt, info = info ).use { alice -> @@ -123,7 +123,7 @@ class RatchetsTest { context = context, authenticationKeypair = bobStaticKeypair, ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = X25519PublicKeyParameters(aliceKeypair.publicKey), + ephemeralPublicKey = aliceKeypair.publicKey, salt = salt, info = info ).let { bob -> @@ -136,7 +136,7 @@ class RatchetsTest { ratchets.ratchetInitAlice( state = aliceState, sk = alice.rk, - bobDhPublicKey = X25519PublicKeyParameters(bobKeypair.publicKey), + bobDhPublicKey = bobKeypair.publicKey, sharedHka = alice.hk, sharedNHka = alice.nhk ) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index 7dae0cf..f7a9954 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -48,8 +48,8 @@ object Cryptography { fun generateKeysNK( context: Context, ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, - authenticationPublicKey: CipherParameters, - ephemeralPublicKey: CipherParameters, + authenticationPublicKey: ByteArray, + ephemeralPublicKey: ByteArray, salt: ByteArray, info: ByteArray, ): NoiseNKKeys { @@ -83,7 +83,7 @@ object Cryptography { context: Context, authenticationKeypair: Protocols.CloseableCurve15519KeyPair, ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, - ephemeralPublicKey: CipherParameters, + ephemeralPublicKey: ByteArray, salt: ByteArray, info: ByteArray, ): Triple { @@ -146,7 +146,7 @@ object Cryptography { fun generateKeysIK( context: Context, ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, - authenticationPublicKey: CipherParameters, + authenticationPublicKey: ByteArray, staticKeyPair: Protocols.CloseableCurve15519KeyPair, info: ByteArray, headerInfo: ByteArray, @@ -223,8 +223,8 @@ object Cryptography { h: ByteArray, ck: ByteArray, ephemeralKeyPair: Protocols.CloseableCurve15519KeyPair, - ephemeralResponderPublicKey: CipherParameters, - authenticationPublicKey: CipherParameters, + ephemeralResponderPublicKey: ByteArray, + authenticationPublicKey: ByteArray, info: ByteArray, headerInfo: ByteArray, ) : NoiseIKKeys { @@ -232,7 +232,7 @@ object Cryptography { // Shadowed vars — use local mutable copies so we can zero them // Note: the incoming h and ck are owned by the caller; don't zero them here - var localH = (h + (ephemeralResponderPublicKey as X25519PublicKeyParameters).encoded).sha256() + var localH = h + ephemeralResponderPublicKey.sha256() var localCk = ck.copyOf() // defensive copy — we'll mutate and zero this val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 65c12b9..6f7c6c3 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -57,7 +57,7 @@ open class Protocols(private val context: Context) { override fun close() { if(isClosed) return publicKey.fill(0) - privateKey?.fill(0) + privateKey?.let{ it.fill(0); privateKey = null} isClosed = true } @@ -80,12 +80,16 @@ open class Protocols(private val context: Context) { } } - fun dh(keypair: CloseableCurve15519KeyPair, publicKey: CipherParameters): ByteArray { + fun dh(keypair: CloseableCurve15519KeyPair, publicKey: ByteArray): ByteArray { val sharedSecret = ByteArray(32) val agreement = X25519Agreement() keypair.use { kp -> agreement.init(X25519PrivateKeyParameters(kp.privateKey, 0)) - agreement.calculateAgreement(publicKey, sharedSecret, 0) + agreement.calculateAgreement( + X25519PublicKeyParameters(publicKey), + sharedSecret, + 0 + ) } return sharedSecret } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index 4b2606c..aff098c 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -27,7 +27,7 @@ class RatchetsHE(context: Context) : Protocols(context){ fun ratchetInitAlice( state: States, sk: ByteArray, - bobDhPublicKey: CipherParameters, + bobDhPublicKey: ByteArray, sharedHka: ByteArray, sharedNHka: ByteArray, ) { @@ -204,7 +204,7 @@ class RatchetsHE(context: Context) : Protocols(context){ state.Nr = 0u state.HKs = state.NHKs state.HKr = state.NHKr - state.DHRr = X25519PublicKeyParameters(header.dh.publicKey) + state.DHRr = header.dh.publicKey val (rk, ck, nhk) = kdfRk(state.RK!!, dh( diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt index f3d6810..9439c5b 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -26,7 +26,7 @@ data class States( var Nr: UByte = 0u, var PN: UByte = 0u, var DHRs: Protocols.CloseableCurve15519KeyPair? = null, - var DHRr: CipherParameters? = null, + var DHRr: ByteArray? = null, var HKs: ByteArray? = null, var HKr: ByteArray? = null, var NHKs: ByteArray? = null, @@ -51,8 +51,7 @@ data class States( NHKs?.let { it.fill(0); NHKs = null } NHKr?.let { it.fill(0); NHKr = null } - (DHRr as? Ed25519PublicKeyParameters)?.encoded?.fill(0) - DHRr = null + DHRr?.let { it.fill(0); DHRr = null } val iterator = MKSKIPPED.entries.iterator() while (iterator.hasNext()) { From 96782608abfb626b34e338a638d7d5b64a4f367e Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Wed, 22 Apr 2026 17:36:49 +0100 Subject: [PATCH 16/19] update: fixed closeables --- .../libsignal_doubleratchet/Cryptography.kt | 20 ++----------------- .../libsignal/Protocols.kt | 5 ----- .../libsignal/States.kt | 5 ----- 3 files changed, 2 insertions(+), 28 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index f7a9954..424d0ae 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -21,7 +21,7 @@ object Cryptography { val rk: ByteArray, val hk: ByteArray, val nhk: ByteArray, - ): Closeable { + ): AutoCloseable { private var zeroed = false override fun close() { @@ -33,14 +33,6 @@ object Cryptography { } } - inline fun use(block: (NoiseNKKeys) -> T): T { - try { - return block(this) - } finally { - close() - } - } - // Prevent accidental logging/serialization of key material override fun toString() = "NoiseNKKeys([REDACTED])" } @@ -117,7 +109,7 @@ object Cryptography { val nhk: ByteArray, val ck: ByteArray? = null, val h: ByteArray? = null, - ): Closeable { + ): AutoCloseable { private var zeroed = false override fun close() { @@ -131,14 +123,6 @@ object Cryptography { } } - inline fun use(block: (NoiseIKKeys) -> T): T { - try { - return block(this) - } finally { - close() - } - } - // Prevent accidental logging/serialization of key material override fun toString() = "NoiseIKKeys([REDACTED])" } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 6f7c6c3..37770e9 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -49,11 +49,6 @@ open class Protocols(private val context: Context) { ): AutoCloseable { private var isClosed = false - fun use(block: (CloseableCurve15519KeyPair) -> Unit) { - if (isClosed) throw IllegalStateException("Cannot use zeroed RatchetState") - block(this) - } - override fun close() { if(isClosed) return publicKey.fill(0) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt index 9439c5b..7422b02 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -68,11 +68,6 @@ data class States( isClosed = true } - fun use(block: (States) -> Unit) { - if (isClosed) throw IllegalStateException("Cannot use zeroed RatchetState") - block(this) - } - companion object { @OptIn(ExperimentalSerializationApi::class) fun deserialize(data: ByteArray): States { From f5b390248ef19b445961b94cf150da77244582a7 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Thu, 23 Apr 2026 13:22:26 +0100 Subject: [PATCH 17/19] update: fixed safety update: changed the use of kdf outputs --- .../libsignal_doubleratchet/Cryptography.kt | 62 +++++++++++------- .../libsignal/Protocols.kt | 35 ++++++----- .../libsignal/RatchetsHE.kt | 63 +++++++++---------- 3 files changed, 90 insertions(+), 70 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index 424d0ae..37e30c7 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -47,15 +47,20 @@ object Cryptography { ): NoiseNKKeys { val protocols = Protocols(context) - val dh1 = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + var dh1: ByteArray? = null + var dh2: ByteArray? = null + + ephemeralKeyPair.use { ekp -> + dh1 = protocols.dh(ekp.privateKey!!, authenticationPublicKey) + dh2 = protocols.dh(ekp.privateKey!!, ephemeralPublicKey) + } var hkdf1: ByteArray? = null var hkdf2: ByteArray? = null try { - hkdf1 = hkdf(ikm = dh1, salt = salt, info = info, len = 32) - hkdf2 = hkdf(ikm = dh2, salt = hkdf1, info = info, len = 96) + hkdf1 = hkdf(ikm = dh1!!, salt = salt, info = info, len = 32) + hkdf2 = hkdf(ikm = dh2!!, salt = hkdf1, info = info, len = 96) return NoiseNKKeys( hkdf2.sliceArray(0 until 32), @@ -63,14 +68,18 @@ object Cryptography { hkdf2.sliceArray(64 until 96), ) } finally { - dh1.fill(0) - dh2.fill(0) + dh1?.fill(0) + dh2?.fill(0) hkdf1?.fill(0) hkdf2?.fill(0) // The sliceArray copies inside Triple are intentionally not zeroed — // they are the return value and owned by the caller } } + + /** + * This exists only for test purposes, do not use for Production builds + */ fun generateKeysNKServer( context: Context, authenticationKeypair: Protocols.CloseableCurve15519KeyPair, @@ -80,8 +89,8 @@ object Cryptography { info: ByteArray, ): Triple { val protocols = Protocols(context) - val dh1 = protocols.dh(authenticationKeypair, ephemeralPublicKey) - val dh2 = protocols.dh(ephemeralKeyPair, ephemeralPublicKey) + val dh1 = protocols.dh(authenticationKeypair.privateKey!!, ephemeralPublicKey) + val dh2 = protocols.dh(ephemeralKeyPair.privateKey!!, ephemeralPublicKey) var hkdf1: ByteArray? = null var hkdf2: ByteArray? = null @@ -140,11 +149,18 @@ object Cryptography { var h = "Noise_IK_25519_AESGCM_SHA256".encodeToByteArray().sha256() var ck = h - h = (h + (authenticationPublicKey as X25519PublicKeyParameters).encoded).sha256() + h = (h + authenticationPublicKey).sha256() h = (h + ephemeralKeyPair.publicKey).sha256() - val dhEs = protocols.dh(ephemeralKeyPair, authenticationPublicKey) - val dhSs = protocols.dh(staticKeyPair, authenticationPublicKey) + var dhEs: ByteArray? = null + var dhSs: ByteArray? = null + + ephemeralKeyPair.use { ekp -> + staticKeyPair.use { skp -> + dhEs = protocols.dh(ekp.privateKey!!, authenticationPublicKey) + dhSs = protocols.dh(skp.privateKey!!, authenticationPublicKey) + } + } // Named references so we can zero them var hkdf1: ByteArray? = null @@ -155,7 +171,7 @@ object Cryptography { var ciphertext: ByteArray? = null try { - hkdf1 = hkdf(ikm = dhEs, salt = ck, info = info, len = 2) + hkdf1 = hkdf(ikm = dhEs!!, salt = ck, info = info, len = 2) ck = hkdf1.sliceArray(0 until 32) k = hkdf1.sliceArray(32 until 64) @@ -166,7 +182,7 @@ object Cryptography { ) h = (h + csPkEnc).sha256() - hkdf2 = hkdf(ikm = dhSs, salt = ck, info = info, len = 2) + hkdf2 = hkdf(ikm = dhSs!!, salt = ck, info = info, len = 2) ck = hkdf2.sliceArray(0 until 32) k.fill(0) // zero previous k before reassigning k = hkdf2.sliceArray(32 until 64) @@ -189,8 +205,8 @@ object Cryptography { ) } finally { // Zero everything sensitive regardless of success or exception - dhEs.fill(0) - dhSs.fill(0) + dhEs?.fill(0) + dhSs?.fill(0) ck.fill(0) k?.fill(0) hkdf1?.fill(0) @@ -219,8 +235,12 @@ object Cryptography { var localH = h + ephemeralResponderPublicKey.sha256() var localCk = ck.copyOf() // defensive copy — we'll mutate and zero this - val dhEe = protocols.dh(ephemeralKeyPair, ephemeralResponderPublicKey) - val dhSe = protocols.dh(ephemeralKeyPair, authenticationPublicKey) + var dhEe: ByteArray? = null + var dhSe: ByteArray? = null + ephemeralKeyPair.use { ekp -> + dhEe = protocols.dh(ekp.privateKey!!, ephemeralResponderPublicKey) + dhSe = protocols.dh(ekp.privateKey!!, authenticationPublicKey) + } var hkdf1: ByteArray? = null var hkdf2: ByteArray? = null @@ -230,7 +250,7 @@ object Cryptography { var ciphertext2: ByteArray? = null try { - hkdf1 = hkdf(ikm = dhEe, salt = localCk, info = info, len = 2) + hkdf1 = hkdf(ikm = dhEe!!, salt = localCk, info = info, len = 2) localCk.fill(0) localCk = hkdf1.sliceArray(0 until 32) k = hkdf1.sliceArray(32 until 64) @@ -242,7 +262,7 @@ object Cryptography { ) localH = (localH + ciphertext1).sha256() - hkdf2 = hkdf(ikm = dhSe, salt = localCk, info = info, len = 2) + hkdf2 = hkdf(ikm = dhSe!!, salt = localCk, info = info, len = 2) localCk.fill(0) localCk = hkdf2.sliceArray(0 until 32) k.fill(0) // zero previous k before reassign @@ -269,8 +289,8 @@ object Cryptography { h = localH ) } finally { - dhEe.fill(0) - dhSe.fill(0) + dhEe?.fill(0) + dhSe?.fill(0) localCk.fill(0) k?.fill(0) hkdf1?.fill(0) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 37770e9..7093df7 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -75,32 +75,33 @@ open class Protocols(private val context: Context) { } } - fun dh(keypair: CloseableCurve15519KeyPair, publicKey: ByteArray): ByteArray { + fun dh(privateKey: ByteArray, publicKey: ByteArray): ByteArray { val sharedSecret = ByteArray(32) val agreement = X25519Agreement() - keypair.use { kp -> - agreement.init(X25519PrivateKeyParameters(kp.privateKey, 0)) - agreement.calculateAgreement( - X25519PublicKeyParameters(publicKey), - sharedSecret, - 0 - ) - } + agreement.init(X25519PrivateKeyParameters(privateKey, 0)) + agreement.calculateAgreement( + X25519PublicKeyParameters(publicKey), + sharedSecret, + 0 + ) + privateKey.fill(0) + publicKey.fill(0) return sharedSecret } fun kdfRk( rk: ByteArray, dhOut: ByteArray - ): Triple { + ): Cryptography.NoiseNKKeys { val info = context.getString(R.string.dr_rk_info).encodeToByteArray() - return hkdf(dhOut, rk, info, 32*3).run { - Triple( - this.sliceArray(0 until 32), - this.sliceArray(32 until 64), - this.sliceArray(64 until 96), - ) - } + val hkdf = hkdf(dhOut, rk, info, 32*3) + val keys = Cryptography.NoiseNKKeys( + hkdf.sliceArray(0 until 32), + hkdf.sliceArray(32 until 64), + hkdf.sliceArray(64 until 96), + ) + hkdf.fill(0) + return keys } fun kdfCk(ck: ByteArray?): Pair { diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index aff098c..e32e43c 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -34,12 +34,15 @@ class RatchetsHE(context: Context) : Protocols(context){ state.DHRs = generateDH() state.DHRr = bobDhPublicKey - kdfRk( - rk = sk, dh( state.DHRs!!, state.DHRr!!) - ).let { - state.RK = it.first - state.CKs = it.second - state.NHKs = it.third + state.DHRs.use { rs -> + val keys = kdfRk( + rk = sk, dh( rs?.privateKey!!, state.DHRr!!) + ) + keys.use { k-> + state.RK = k.rk + state.CKs = k.hk + state.NHKs = k.nhk + } } state.CKr = null @@ -206,38 +209,34 @@ class RatchetsHE(context: Context) : Protocols(context){ state.HKr = state.NHKr state.DHRr = header.dh.publicKey - val (rk, ck, nhk) = kdfRk(state.RK!!, - dh( - state.DHRs!!, - state.DHRr!!, + state.DHRs.use { rs -> + val keys = kdfRk(state.RK!!, + dh( + rs?.privateKey!!, + state.DHRr!!, + ) ) - ) - try { - state.RK = rk.copyOf() - state.CKr = ck.copyOf() - state.NHKr = nhk.copyOf() - } finally { - rk.fill(0) - ck.fill(0) - nhk.fill(0) + keys.use { k -> + state.RK = k.rk + state.CKr = k.hk + state.NHKr = k.nhk + } } state.DHRs = generateDH() - val (rk1, ck1, nhk1) = kdfRk(state.RK!!, - dh( - state.DHRs!!, - state.DHRr!!, + state.DHRs.use { rs -> + val keys = kdfRk(state.RK!!, + dh( + rs?.privateKey!!, + state.DHRr!!, + ) ) - ) - try { - state.RK = rk1.copyOf() - state.CKs = ck1.copyOf() - state.NHKs = nhk1.copyOf() - } finally { - rk1.fill(0) - ck1.fill(0) - nhk1.fill(0) + keys.use { k-> + state.RK = k.rk + state.CKs = k.hk + state.NHKs = k.nhk + } } } } \ No newline at end of file From 855be82c7f1b5eb602cface10dd72fedd93f25c9 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Thu, 23 Apr 2026 16:16:50 +0100 Subject: [PATCH 18/19] update: modified to use GCM update: better zero mec --- .../libsignal/RatchetsTest.kt | 154 +++++++++--------- .../libsignal_doubleratchet/Cryptography.kt | 45 ++++- .../libsignal/Protocols.kt | 146 ++++++++++------- .../libsignal/RatchetsHE.kt | 64 ++++---- 4 files changed, 247 insertions(+), 162 deletions(-) diff --git a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt index 52506c3..9328291 100644 --- a/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt +++ b/double_ratchet/src/androidTest/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsTest.kt @@ -19,98 +19,106 @@ class RatchetsTest { InstrumentationRegistry.getInstrumentation().targetContext val protocol = Protocols(context) - val aliceKeypair = protocol.generateDH() - val bobStaticKeypair = protocol.generateDH() - val bobKeypair = protocol.generateDH() val salt = "completeRatchetTest_v1".encodeToByteArray() - val info = context.generateRandomBytes(16) + - aliceKeypair.publicKey + - bobKeypair.publicKey + - bobStaticKeypair.publicKey @Test fun completeRatchetTest() { - Cryptography.generateKeysNK( - context = context, - ephemeralKeyPair = aliceKeypair, - authenticationPublicKey = bobStaticKeypair.publicKey, - ephemeralPublicKey = bobKeypair.publicKey, - salt = salt, - info = info - ).use { alice -> - Cryptography.generateKeysNKServer( - context = context, - authenticationKeypair = bobStaticKeypair, - ephemeralKeyPair = bobKeypair, - ephemeralPublicKey = aliceKeypair.publicKey, - salt = salt, - info = info - ).let { bob -> - assertArrayEquals(alice.rk, bob.first) - assertArrayEquals(alice.hk, bob.second) - assertArrayEquals(alice.nhk, bob.third) - - val ratchets = RatchetsHE(context) - val aliceState = States() - ratchets.ratchetInitAlice( - state = aliceState, - sk = alice.rk, - bobDhPublicKey = bobKeypair.publicKey, - sharedHka = alice.hk, - sharedNHka = alice.nhk + val aliceKeypair = protocol.generateDH() + val bobStaticKeypair = protocol.generateDH() + val bobKeypair = protocol.generateDH() +// val info = context.generateRandomBytes(16) + +// aliceKeypair.publicKey + +// bobKeypair.publicKey + +// bobStaticKeypair.publicKey + val info = ByteArray(32) + + val ad = "RatchetsTest".encodeToByteArray().sha256() + val originalText = SecureRandom.getSeed(32); + var ratchetPayload: RatchetPayload? + + aliceKeypair.use { aliceKeypair -> + bobKeypair.use { bobKeypair -> + + val alicePublicKey = aliceKeypair.publicKey.copyOf() + val bobPublicKey = bobKeypair.publicKey.copyOf() + val authenticationPublicKey = bobStaticKeypair.publicKey.copyOf() + + val aliceKey = Cryptography.generateKeysNK( + context = context, + ephemeralKeyPair = aliceKeypair, + authenticationPublicKey = authenticationPublicKey, + ephemeralPublicKey = bobPublicKey, + salt = salt, + info = info ) - val bobState = States() - ratchets.ratchetInitBob( - state = bobState, - sk = bob.first, - bobKeypair = bobKeypair, - sharedHka = bob.second, - sharedNHka = bob.third + val bob = Cryptography.generateKeysNKServer( + context = context, + authenticationKeypair = bobStaticKeypair, + ephemeralKeyPair = bobKeypair, + ephemeralPublicKey = alicePublicKey, + salt = salt, + info = info ) - val originalText = SecureRandom.getSeed(32); - val ad = "RatchetsTest".encodeToByteArray().sha256() - var ratchetPayload = ratchets.ratchetEncrypt( - state = aliceState, - plaintext = originalText, - ad = ad - ) - - var plaintext = ratchets.ratchetDecrypt( - state = bobState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - - assertArrayEquals(originalText, plaintext) + val ratchets = RatchetsHE(context) - ratchetPayload = ratchets.ratchetEncrypt( - state = bobState, - plaintext = originalText, - ad = ad - ) + aliceKey.use { alice -> + assertArrayEquals(alice.rk, bob.first) + assertArrayEquals(alice.hk, bob.second) + assertArrayEquals(alice.nhk, bob.third) + + val aliceState = States() + aliceState.use { aliceState -> + ratchets.ratchetInitAlice( + state = aliceState, + sk = alice.rk, + bobDhPublicKey = bobPublicKey.copyOf(), + sharedHka = alice.hk, + sharedNHka = alice.nhk + ) + + ratchetPayload = ratchets.ratchetEncrypt( + state = aliceState, + plaintext = originalText, + ad = ad + ) + } + } - plaintext = ratchets.ratchetDecrypt( - state = aliceState, - encHeader = ratchetPayload.header, - cipherText = ratchetPayload.cipherText, - ad = ad - ) - assertArrayEquals(originalText, plaintext) + val bobState = States() + bobState.use { bobState -> + ratchets.ratchetInitBob( + state = bobState, + sk = bob.first, + bobKeypair = bobKeypair, + sharedHka = bob.second, + sharedNHka = bob.third + ) + val plaintext = ratchets.ratchetDecrypt( + state = bobState, + encHeader = ratchetPayload!!.header, + cipherText = ratchetPayload.cipherText, + ad = ad + ) + assertArrayEquals(originalText, plaintext) + } } - } - - } @Test fun completeRatchetOutOfOrderTest() { + val aliceKeypair = protocol.generateDH() + val bobStaticKeypair = protocol.generateDH() + val bobKeypair = protocol.generateDH() + val info = context.generateRandomBytes(16) + + aliceKeypair.publicKey + + bobKeypair.publicKey + + bobStaticKeypair.publicKey Cryptography.generateKeysNK( context = context, ephemeralKeyPair = aliceKeypair, diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt index 37e30c7..b31b80b 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/Cryptography.kt @@ -13,6 +13,7 @@ import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import java.security.SecureRandom +import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec object Cryptography { @@ -362,7 +363,49 @@ object Cryptography { cipher.init(Cipher.DECRYPT_MODE, key, spec) associatedData?.let { cipher.updateAAD(it) } - return cipher.doFinal(ciphertext) + return try { + cipher.doFinal(ciphertext) + } catch (e: Exception) { + e.printStackTrace() + throw e + } + } + } + + object AesCbc { + private const val ALGORITHM = "AES/CBC/PKCS5Padding" + private const val IV_SIZE = 16 // AES block size is always 16 bytes + + fun encrypt(key: ByteArray, plaintext: ByteArray, iv: ByteArray? = null): ByteArray { + val cipher = Cipher.getInstance(ALGORITHM) + + val finalIv = iv ?: ByteArray(IV_SIZE).apply { SecureRandom().nextBytes(this) } + val keySpec = SecretKeySpec(key, "AES") + val ivSpec = IvParameterSpec(finalIv) + + cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec) + val ciphertext = cipher.doFinal(plaintext) + + return if(iv == null) { + finalIv + ciphertext + } else { + ciphertext + } + } + + fun decrypt( + key: ByteArray, + ciphertext: ByteArray, + iv: ByteArray + ): ByteArray { + val cipher = Cipher.getInstance(ALGORITHM) + val keySpec = SecretKeySpec(key, "AES") + + val ivSpec = IvParameterSpec(iv) + cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec) + + val plaintext = cipher.doFinal(ciphertext) + return plaintext } } } \ No newline at end of file diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 7093df7..8706f3f 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -80,12 +80,10 @@ open class Protocols(private val context: Context) { val agreement = X25519Agreement() agreement.init(X25519PrivateKeyParameters(privateKey, 0)) agreement.calculateAgreement( - X25519PublicKeyParameters(publicKey), + X25519PublicKeyParameters(publicKey, 0), sharedSecret, 0 ) - privateKey.fill(0) - publicKey.fill(0) return sharedSecret } @@ -118,25 +116,33 @@ open class Protocols(private val context: Context) { plainText: ByteArray, ad: ByteArray, ): ByteArray { - val len = 80 - return hkdf( + val len = 76 + val hkdfOutput = hkdf( ikm = mk, salt = ByteArray(len), info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), len = len, - ).run { - val key = this.sliceArray(0 until 32) - val authKey = this.sliceArray(32 until 64) - val iv = this.sliceArray(64 until 80) - - val cipherText = Cryptography.AesGcm.encrypt( - key = SecretKeySpec(key, "AES"), - iv = iv, - plaintext = plainText, - ) - val mac = hmac(authKey) - mac.update(ad + cipherText) - cipherText + mac.doFinal() + ) + try { + val key = hkdfOutput.sliceArray(0 until 32) + val authKey = hkdfOutput.sliceArray(32 until 64) + val iv = hkdfOutput.sliceArray(64 until 76) + + try { + val cipherText = Cryptography.AesGcm.encrypt( + key = SecretKeySpec(key, "AES"), + iv = iv, + plaintext = plainText, + ) + val mac = hmac(authKey) + mac.update(ad + cipherText) + return cipherText + mac.doFinal() + } finally { + key.fill(0) + iv.fill(0) + } + } finally { + hkdfOutput.fill(0) } } @@ -144,38 +150,48 @@ open class Protocols(private val context: Context) { mk: ByteArray, plainText: ByteArray, ): ByteArray { - val len = 80 - return hkdf( + val len = 76 + val hkdfOutputs = hkdf( ikm = mk, salt = ByteArray(len), info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), len = len, - ).run { - val key = this.sliceArray(0 until 32) - val authKey = this.sliceArray(32 until 64) - val iv = this.sliceArray(64 until 80) - - val cipherText = Cryptography.AesGcm.encrypt( - key = SecretKeySpec(key, "AES"), - iv = iv, - plaintext = plainText, - ) + ) - val mac = hmac(authKey) - mac.update(cipherText) - cipherText + mac.doFinal() + try { + val key = hkdfOutputs.sliceArray(0 until 32) + val authKey = hkdfOutputs.sliceArray(32 until 64) + val iv = hkdfOutputs.sliceArray(64 until 76) + + try { + val cipherText = Cryptography.AesGcm.encrypt( + key = SecretKeySpec(key, "AES"), + iv = iv, + plaintext = plainText, + ) + val mac = hmac(authKey) + mac.update(cipherText) + return cipherText + mac.doFinal() + } finally { + key.fill(0) + iv.fill(0) + } + } finally { + hkdfOutputs.fill(0) } } fun decrypt(mk: ByteArray, cipherText: ByteArray, ad: ByteArray): ByteArray { - val len = 80 - return hkdf( + val len = 76 + val hkdfOutput = hkdf( ikm = mk, salt = ByteArray(len), info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), len = len, - ).run { - val authKey = this.sliceArray(32 until 64) + ) + + try { + val authKey = hkdfOutput.sliceArray(32 until 64) val plaintextCiphertext = cipherText.dropLast(MAC_LEN).toByteArray() val mac = hmac(authKey) @@ -186,27 +202,36 @@ open class Protocols(private val context: Context) { throw Exception("Message failed authentication") } - val key = this.sliceArray(0 until 32) - val iv = this.sliceArray(64 until 80) - Cryptography.AesGcm.decrypt( - key = SecretKeySpec(key, "AES"), - ciphertext = plaintextCiphertext, - iv = iv, - ) + val key = hkdfOutput.sliceArray(0 until 32) + val iv = hkdfOutput.sliceArray(64 until 76) + try { + return Cryptography.AesGcm.decrypt( + key = SecretKeySpec(key, "AES"), + ciphertext = plaintextCiphertext, + iv = iv, + ) + } finally { + key.fill(0) + iv.fill(0) + } + } finally { + hkdfOutput.fill(0) } } fun hDecrypt(mk: ByteArray?, cipherText: ByteArray): ByteArray? { - val len = 80 + val len = 76 if(mk == null) return null - return hkdf( + val hkdfOutputs = hkdf( ikm = mk, salt = ByteArray(len), info = context.getString(R.string.dr_encrypt_info).encodeToByteArray(), len = len, - ).run { - val authKey = this.sliceArray(32 until 64) + ) + + try { + val authKey = hkdfOutputs.sliceArray(32 until 64) val mac = hmac(authKey) val plainCiphertext = cipherText.dropLast(MAC_LEN).toByteArray() @@ -217,13 +242,24 @@ open class Protocols(private val context: Context) { throw Exception("Message failed authentication") } - val key = this.sliceArray(0 until 32) - val iv = this.sliceArray(64 until 80) - Cryptography.AesGcm.decrypt( - key = SecretKeySpec(key, "AES"), - ciphertext = plainCiphertext, - iv = iv, - ) + val key = hkdfOutputs.sliceArray(0 until 32) + val iv = hkdfOutputs.sliceArray(64 until 76) + return try { + Cryptography.AesGcm.decrypt( + key = SecretKeySpec(key, "AES"), + ciphertext = plainCiphertext, + iv = iv, + ) + } catch (e: Exception){ + e.fillInStackTrace() + throw e + } finally { + key.fill(0) + iv.fill(0) + authKey.fill(0) + } + } finally { + hkdfOutputs.fill(0) } } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index e32e43c..5a54515 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -34,15 +34,13 @@ class RatchetsHE(context: Context) : Protocols(context){ state.DHRs = generateDH() state.DHRr = bobDhPublicKey - state.DHRs.use { rs -> - val keys = kdfRk( - rk = sk, dh( rs?.privateKey!!, state.DHRr!!) - ) - keys.use { k-> - state.RK = k.rk - state.CKs = k.hk - state.NHKs = k.nhk - } + val keys = kdfRk( + rk = sk, dh( state.DHRs?.privateKey!!, state.DHRr!!) + ) + keys.use { k-> + state.RK = k.rk + state.CKs = k.hk + state.NHKs = k.nhk } state.CKr = null @@ -194,8 +192,12 @@ class RatchetsHE(context: Context) : Protocols(context){ return Pair(header, false) } - header = hDecrypt(state.NHKr!!, encHeader)?.run { - Headers.deserialize(this) + val decryptedHeader = hDecrypt(state.NHKr!!, encHeader) + try { + if(decryptedHeader == null) throw Exception("Header is null") + header = Headers.deserialize(decryptedHeader) + } finally { + decryptedHeader?.fill(0) } return Pair(header, true) @@ -209,34 +211,30 @@ class RatchetsHE(context: Context) : Protocols(context){ state.HKr = state.NHKr state.DHRr = header.dh.publicKey - state.DHRs.use { rs -> - val keys = kdfRk(state.RK!!, - dh( - rs?.privateKey!!, - state.DHRr!!, - ) + var keys = kdfRk(state.RK!!, + dh( + state.DHRs?.privateKey!!, + state.DHRr!!, ) - keys.use { k -> - state.RK = k.rk - state.CKr = k.hk - state.NHKr = k.nhk - } + ) + keys.use { k -> + state.RK = k.rk + state.CKr = k.hk + state.NHKr = k.nhk } state.DHRs = generateDH() - state.DHRs.use { rs -> - val keys = kdfRk(state.RK!!, - dh( - rs?.privateKey!!, - state.DHRr!!, - ) + keys = kdfRk(state.RK!!, + dh( + state.DHRs?.privateKey!!, + state.DHRr!!, ) - keys.use { k-> - state.RK = k.rk - state.CKs = k.hk - state.NHKs = k.nhk - } + ) + keys.use { k-> + state.RK = k.rk + state.CKs = k.hk + state.NHKs = k.nhk } } } \ No newline at end of file From c4a12f8fcd966f2c52427e512e417b76028362e3 Mon Sep 17 00:00:00 2001 From: sherlockwisdom Date: Thu, 23 Apr 2026 17:20:44 +0100 Subject: [PATCH 19/19] update: serializing states --- .../libsignal_doubleratchet/libsignal/Protocols.kt | 2 ++ .../libsignal_doubleratchet/libsignal/RatchetsHE.kt | 7 ++++--- .../libsignal_doubleratchet/libsignal/States.kt | 11 +++++++++-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt index 8706f3f..c49d5ec 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/Protocols.kt @@ -8,6 +8,7 @@ import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoUtils.hmac import com.afkanerd.smswithoutborders.libsignal_doubleratchet.Cryptography import com.afkanerd.smswithoutborders.libsignal_doubleratchet.R import com.google.common.primitives.Bytes +import kotlinx.serialization.Serializable import org.bouncycastle.crypto.AsymmetricCipherKeyPair import org.bouncycastle.crypto.CipherParameters import org.bouncycastle.crypto.agreement.X25519Agreement @@ -43,6 +44,7 @@ open class Protocols(private val context: Context) { Security.addProvider(BouncyCastleProvider()) } + @Serializable data class CloseableCurve15519KeyPair( var publicKey: ByteArray, var privateKey: ByteArray? diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt index 5a54515..ce3380f 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/RatchetsHE.kt @@ -138,7 +138,7 @@ class RatchetsHE(context: Context) : Protocols(context){ try { state.CKr = ck val mk = mk - state.MKSKIPPED[Pair(state.HKr, state.Nr.toInt())] = mk + state.MKSKIPPED[MKSkippedPair(state.HKr, state.Nr.toInt())] = mk state.Nr++ } finally { ck.fill(0) @@ -155,7 +155,8 @@ class RatchetsHE(context: Context) : Protocols(context){ ad: ByteArray ) : ByteArray? { state.MKSKIPPED.forEach { - val (hk, n) = it.key + val hk = it.key.key + val n = it.key.count val mk = it.value try { @@ -167,7 +168,7 @@ class RatchetsHE(context: Context) : Protocols(context){ return decrypt(mk, ciphertext, concat(ad, encHeader)) } } finally { - hk.fill(0) + hk?.fill(0) mk.fill(0) } } diff --git a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt index 7422b02..5f0c780 100644 --- a/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt +++ b/double_ratchet/src/main/java/com/afkanerd/smswithoutborders/libsignal_doubleratchet/libsignal/States.kt @@ -18,6 +18,13 @@ import java.security.PrivateKey import java.security.PublicKey +@Serializable +data class MKSkippedPair( + val key: ByteArray?, + val count: Int +) + +@Serializable data class States( var RK: ByteArray? = null, var CKs: ByteArray? = null, @@ -31,7 +38,7 @@ data class States( var HKr: ByteArray? = null, var NHKs: ByteArray? = null, var NHKr: ByteArray? = null, - var MKSKIPPED: MutableMap, ByteArray> = mutableMapOf() + var MKSKIPPED: MutableMap = mutableMapOf() ) : AutoCloseable { @OptIn(ExperimentalSerializationApi::class) fun serialize(): ByteArray { @@ -56,7 +63,7 @@ data class States( val iterator = MKSKIPPED.entries.iterator() while (iterator.hasNext()) { val entry = iterator.next() - entry.key.first.fill(0) + entry.key.key?.fill(0) entry.value.fill(0) iterator.remove() }