1package com.peachpasswords.sync23import org.bouncycastle.crypto.InvalidCipherTextException4import org.bouncycastle.crypto.digests.Blake2sDigest5import org.bouncycastle.crypto.generators.HKDFBytesGenerator6import org.bouncycastle.crypto.modes.ChaCha20Poly13057import org.bouncycastle.crypto.params.AEADParameters8import org.bouncycastle.crypto.params.HKDFParameters9import org.bouncycastle.crypto.params.KeyParameter10import org.bouncycastle.crypto.params.X25519PrivateKeyParameters11import org.bouncycastle.crypto.params.X25519PublicKeyParameters12import java.nio.ByteBuffer13import java.nio.ByteOrder14import java.security.SecureRandom1516private const val PROTOCOL_NAME = "Noise_XX_25519_ChaChaPoly_BLAKE2s"1718private fun initHash(): ByteArray {19 val nameBytes = PROTOCOL_NAME.encodeToByteArray()20 if (nameBytes.size <= 32) {21 return ByteArray(32).also { nameBytes.copyInto(it) }22 }23 24 25 26 val blake = Blake2sDigest(256)27 blake.update(nameBytes, 0, nameBytes.size)28 val out = ByteArray(32)29 blake.doFinal(out, 0)30 return out31}3233private fun mixHash(h: ByteArray, data: ByteArray): ByteArray {34 val blake = Blake2sDigest(256)35 blake.update(h, 0, h.size)36 blake.update(data, 0, data.size)37 val out = ByteArray(32)38 blake.doFinal(out, 0)39 return out40}4142private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {43 44 val generator = HKDFBytesGenerator(Blake2sDigest(256))45 generator.init(HKDFParameters(ikm, ck, ByteArray(0)))46 val out = ByteArray(64)47 generator.generateBytes(out, 0, out.size)48 return out.copyOfRange(0, 32) to out.copyOfRange(32, 64)49}50515253internal fun noiseXXInitHashForTest(): ByteArray = initHash()54internal fun noiseXXHkdf2ForTest(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> = hkdf2(ck, ikm)5556private fun nonceBytes(n: Long): ByteArray {57 val buf = ByteArray(12)58 ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).putLong(4, n)59 return buf60}6162interface NoiseXXSession {63 fun encrypt(plaintext: ByteArray): ByteArray64 fun decrypt(ciphertext: ByteArray): ByteArray65 val remoteStaticPublicKey: ByteArray66 val handshakeHash: ByteArray67}6869private data class X25519KeyPair(70 val publicKey: ByteArray,71 val secretKey: ByteArray,72)7374private fun generateKeyPair(): X25519KeyPair {75 val priv = X25519PrivateKeyParameters(SecureRandom())76 return X25519KeyPair(77 publicKey = priv.generatePublicKey().encoded,78 secretKey = priv.encoded,79 )80}8182private fun sharedKey(privateKey: ByteArray, publicKey: ByteArray): ByteArray {83 val priv = X25519PrivateKeyParameters(privateKey, 0)84 val pub = X25519PublicKeyParameters(publicKey, 0)85 val out = ByteArray(32)86 priv.generateSecret(pub, out, 0)87 return out88}8990private fun chachaSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {91 val cipher = ChaCha20Poly1305()92 cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce, aad))93 val out = ByteArray(cipher.getOutputSize(plaintext.size))94 var len = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)95 len += cipher.doFinal(out, len)96 return out.copyOf(len)97}9899private fun chachaOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray? {100 return try {101 val cipher = ChaCha20Poly1305()102 cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce, aad))103 val out = ByteArray(cipher.getOutputSize(ciphertext.size))104 var len = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)105 len += cipher.doFinal(out, len)106 out.copyOf(len)107 } catch (_: InvalidCipherTextException) {108 null109 }110}111112suspend fun noiseXXInitiator(113 ourStaticPrivateKey: ByteArray,114 ourStaticPublicKey: ByteArray,115 send: suspend (ByteArray) -> Unit,116 receive: suspend () -> ByteArray,117): NoiseXXSession {118 var h = initHash()119 var ck = h.copyOf()120121 val e = generateKeyPair()122 h = mixHash(h, e.publicKey)123 send(e.publicKey)124125 val msg2 = receive()126 require(msg2.size >= 32 + 32 + 16 + 16) { "Noise XX: msg2 too short" }127 val remoteEphemeral = msg2.copyOfRange(0, 32)128 val encryptedStatic = msg2.copyOfRange(32, 32 + 32 + 16)129 val encryptedPayload = msg2.copyOfRange(32 + 32 + 16, msg2.size)130131 h = mixHash(h, remoteEphemeral)132 val ee = sharedKey(e.secretKey, remoteEphemeral)133 val (ck1, k1) = hkdf2(ck, ee)134 ck = ck1135136 val remoteStaticPlain = chachaOpen(k1, nonceBytes(0L), encryptedStatic, h)137 ?: throw IllegalStateException("Noise XX: msg2 static auth failed")138 require(remoteStaticPlain.size == 32) { "Noise XX: msg2 static auth failed" }139 h = mixHash(h, encryptedStatic)140141 val es = sharedKey(e.secretKey, remoteStaticPlain)142 val (ck2, k2) = hkdf2(ck, es)143 ck = ck2144145 val payloadPlain = chachaOpen(k2, nonceBytes(0L), encryptedPayload, h)146 ?: throw IllegalStateException("Noise XX: msg2 payload auth failed")147 h = mixHash(h, encryptedPayload)148 @Suppress("UNUSED_VARIABLE")149 val _payloadPlain = payloadPlain150151 val encryptedOurStatic = chachaSeal(k2, nonceBytes(1L), ourStaticPublicKey, h)152 h = mixHash(h, encryptedOurStatic)153154 val se = sharedKey(ourStaticPrivateKey, remoteEphemeral)155 val (ck3, k3) = hkdf2(ck, se)156 ck = ck3157158 val encryptedFinalPayload = chachaSeal(k3, nonceBytes(0L), ByteArray(0), h)159 h = mixHash(h, encryptedFinalPayload)160161 val msg3 = ByteArray(encryptedOurStatic.size + encryptedFinalPayload.size)162 encryptedOurStatic.copyInto(msg3, 0)163 encryptedFinalPayload.copyInto(msg3, encryptedOurStatic.size)164 send(msg3)165166 val (initSend, respSend) = hkdf2(ck, ByteArray(0))167 val sendCipher = initSend168 val recvCipher = respSend169 var sendNonce = 0L170 var recvNonce = 0L171172 return object : NoiseXXSession {173 override fun encrypt(plaintext: ByteArray): ByteArray {174 return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))175 }176177 override fun decrypt(ciphertext: ByteArray): ByteArray {178 return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))179 ?: throw IllegalStateException("Noise XX: decryption failed")180 }181182 override val remoteStaticPublicKey: ByteArray = remoteStaticPlain183 override val handshakeHash: ByteArray = h.copyOf()184 }185}186187suspend fun noiseXXResponder(188 ourStaticPrivateKey: ByteArray,189 ourStaticPublicKey: ByteArray,190 send: suspend (ByteArray) -> Unit,191 receive: suspend () -> ByteArray,192): NoiseXXSession {193 var h = initHash()194 var ck = h.copyOf()195196 val msg1 = receive()197 require(msg1.size >= 32) { "Noise XX: msg1 too short" }198 val remoteEphemeral = msg1.copyOfRange(0, 32)199 h = mixHash(h, remoteEphemeral)200201 val e = generateKeyPair()202 h = mixHash(h, e.publicKey)203 val ee = sharedKey(e.secretKey, remoteEphemeral)204 val (ck1, k1) = hkdf2(ck, ee)205 ck = ck1206207 val encryptedOurStatic = chachaSeal(k1, nonceBytes(0L), ourStaticPublicKey, h)208 h = mixHash(h, encryptedOurStatic)209210 val es = sharedKey(ourStaticPrivateKey, remoteEphemeral)211 val (ck2, k2) = hkdf2(ck, es)212 ck = ck2213214 val encryptedPayload = chachaSeal(k2, nonceBytes(0L), ByteArray(0), h)215 h = mixHash(h, encryptedPayload)216217 val msg2 = ByteArray(e.publicKey.size + encryptedOurStatic.size + encryptedPayload.size)218 e.publicKey.copyInto(msg2, 0)219 encryptedOurStatic.copyInto(msg2, e.publicKey.size)220 encryptedPayload.copyInto(msg2, e.publicKey.size + encryptedOurStatic.size)221 send(msg2)222223 val msg3 = receive()224 require(msg3.size >= 32 + 16 + 16) { "Noise XX: msg3 too short" }225 val encryptedRemoteStatic = msg3.copyOfRange(0, 32 + 16)226 val encryptedFinalPayload = msg3.copyOfRange(32 + 16, msg3.size)227228 val remoteStaticPlain = chachaOpen(k2, nonceBytes(1L), encryptedRemoteStatic, h)229 ?: throw IllegalStateException("Noise XX: msg3 static auth failed")230 require(remoteStaticPlain.size == 32) { "Noise XX: msg3 static auth failed" }231 h = mixHash(h, encryptedRemoteStatic)232233 val se = sharedKey(e.secretKey, remoteStaticPlain)234 val (ck3, k3) = hkdf2(ck, se)235 ck = ck3236237 val finalPayloadPlain = chachaOpen(k3, nonceBytes(0L), encryptedFinalPayload, h)238 ?: throw IllegalStateException("Noise XX: msg3 final payload auth failed")239 h = mixHash(h, encryptedFinalPayload)240 @Suppress("UNUSED_VARIABLE")241 val _finalPayloadPlain = finalPayloadPlain242243 val (initSend, respSend) = hkdf2(ck, ByteArray(0))244 val sendCipher = respSend245 val recvCipher = initSend246 var sendNonce = 0L247 var recvNonce = 0L248249 return object : NoiseXXSession {250 override fun encrypt(plaintext: ByteArray): ByteArray {251 return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))252 }253254 override fun decrypt(ciphertext: ByteArray): ByteArray {255 return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))256 ?: throw IllegalStateException("Noise XX: decryption failed")257 }258259 override val remoteStaticPublicKey: ByteArray = remoteStaticPlain260 override val handshakeHash: ByteArray = h.copyOf()261 }262}