1package com.peachpasswords.sync23import org.bouncycastle.crypto.InvalidCipherTextException4import org.bouncycastle.crypto.digests.Blake2sDigest5import org.bouncycastle.crypto.digests.SHA256Digest6import org.bouncycastle.crypto.generators.HKDFBytesGenerator7import org.bouncycastle.crypto.modes.ChaCha20Poly13058import org.bouncycastle.crypto.params.AEADParameters9import org.bouncycastle.crypto.params.HKDFParameters10import org.bouncycastle.crypto.params.KeyParameter11import org.bouncycastle.crypto.params.X25519PrivateKeyParameters12import org.bouncycastle.crypto.params.X25519PublicKeyParameters13import java.nio.ByteBuffer14import java.nio.ByteOrder15import java.security.SecureRandom1617private const val PROTOCOL_NAME = "Noise_XX_25519_ChaChaPoly_BLAKE2s"1819private fun initHash(): ByteArray {20 val nameBytes = PROTOCOL_NAME.encodeToByteArray()21 if (nameBytes.size <= 32) {22 return ByteArray(32).also { nameBytes.copyInto(it) }23 }24 val sha = SHA256Digest()25 sha.update(nameBytes, 0, nameBytes.size)26 val out = ByteArray(32)27 sha.doFinal(out, 0)28 return out29}3031private fun mixHash(h: ByteArray, data: ByteArray): ByteArray {32 val blake = Blake2sDigest(256)33 blake.update(h, 0, h.size)34 blake.update(data, 0, data.size)35 val out = ByteArray(32)36 blake.doFinal(out, 0)37 return out38}3940private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {41 val generator = HKDFBytesGenerator(SHA256Digest())42 generator.init(HKDFParameters(ikm, ck, ByteArray(0)))43 val out = ByteArray(64)44 generator.generateBytes(out, 0, out.size)45 return out.copyOfRange(0, 32) to out.copyOfRange(32, 64)46}4748private fun nonceBytes(n: Long): ByteArray {49 val buf = ByteArray(12)50 ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).putLong(4, n)51 return buf52}5354interface NoiseXXSession {55 fun encrypt(plaintext: ByteArray): ByteArray56 fun decrypt(ciphertext: ByteArray): ByteArray57 val remoteStaticPublicKey: ByteArray58 val handshakeHash: ByteArray59}6061private data class X25519KeyPair(62 val publicKey: ByteArray,63 val secretKey: ByteArray,64)6566private fun generateKeyPair(): X25519KeyPair {67 val priv = X25519PrivateKeyParameters(SecureRandom())68 return X25519KeyPair(69 publicKey = priv.generatePublicKey().encoded,70 secretKey = priv.encoded,71 )72}7374private fun sharedKey(privateKey: ByteArray, publicKey: ByteArray): ByteArray {75 val priv = X25519PrivateKeyParameters(privateKey, 0)76 val pub = X25519PublicKeyParameters(publicKey, 0)77 val out = ByteArray(32)78 priv.generateSecret(pub, out, 0)79 return out80}8182private fun chachaSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {83 val cipher = ChaCha20Poly1305()84 cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce, aad))85 val out = ByteArray(cipher.getOutputSize(plaintext.size))86 var len = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)87 len += cipher.doFinal(out, len)88 return out.copyOf(len)89}9091private fun chachaOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray? {92 return try {93 val cipher = ChaCha20Poly1305()94 cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce, aad))95 val out = ByteArray(cipher.getOutputSize(ciphertext.size))96 var len = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)97 len += cipher.doFinal(out, len)98 out.copyOf(len)99 } catch (_: InvalidCipherTextException) {100 null101 }102}103104suspend fun noiseXXInitiator(105 ourStaticPrivateKey: ByteArray,106 ourStaticPublicKey: ByteArray,107 send: suspend (ByteArray) -> Unit,108 receive: suspend () -> ByteArray,109): NoiseXXSession {110 var h = initHash()111 var ck = h.copyOf()112113 val e = generateKeyPair()114 h = mixHash(h, e.publicKey)115 send(e.publicKey)116117 val msg2 = receive()118 require(msg2.size >= 32 + 32 + 16 + 16) { "Noise XX: msg2 too short" }119 val remoteEphemeral = msg2.copyOfRange(0, 32)120 val encryptedStatic = msg2.copyOfRange(32, 32 + 32 + 16)121 val encryptedPayload = msg2.copyOfRange(32 + 32 + 16, msg2.size)122123 h = mixHash(h, remoteEphemeral)124 val ee = sharedKey(e.secretKey, remoteEphemeral)125 val (ck1, k1) = hkdf2(ck, ee)126 ck = ck1127128 val remoteStaticPlain = chachaOpen(k1, nonceBytes(0L), encryptedStatic, h)129 ?: throw IllegalStateException("Noise XX: msg2 static auth failed")130 require(remoteStaticPlain.size == 32) { "Noise XX: msg2 static auth failed" }131 h = mixHash(h, encryptedStatic)132133 val es = sharedKey(e.secretKey, remoteStaticPlain)134 val (ck2, k2) = hkdf2(ck, es)135 ck = ck2136137 val payloadPlain = chachaOpen(k2, nonceBytes(0L), encryptedPayload, h)138 ?: throw IllegalStateException("Noise XX: msg2 payload auth failed")139 h = mixHash(h, encryptedPayload)140 @Suppress("UNUSED_VARIABLE")141 val _payloadPlain = payloadPlain142143 val encryptedOurStatic = chachaSeal(k2, nonceBytes(1L), ourStaticPublicKey, h)144 h = mixHash(h, encryptedOurStatic)145146 val se = sharedKey(ourStaticPrivateKey, remoteEphemeral)147 val (ck3, k3) = hkdf2(ck, se)148 ck = ck3149150 val encryptedFinalPayload = chachaSeal(k3, nonceBytes(0L), ByteArray(0), h)151 h = mixHash(h, encryptedFinalPayload)152153 val msg3 = ByteArray(encryptedOurStatic.size + encryptedFinalPayload.size)154 encryptedOurStatic.copyInto(msg3, 0)155 encryptedFinalPayload.copyInto(msg3, encryptedOurStatic.size)156 send(msg3)157158 val (initSend, respSend) = hkdf2(ck, ByteArray(0))159 val sendCipher = initSend160 val recvCipher = respSend161 var sendNonce = 0L162 var recvNonce = 0L163164 return object : NoiseXXSession {165 override fun encrypt(plaintext: ByteArray): ByteArray {166 return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))167 }168169 override fun decrypt(ciphertext: ByteArray): ByteArray {170 return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))171 ?: throw IllegalStateException("Noise XX: decryption failed")172 }173174 override val remoteStaticPublicKey: ByteArray = remoteStaticPlain175 override val handshakeHash: ByteArray = h.copyOf()176 }177}178179suspend fun noiseXXResponder(180 ourStaticPrivateKey: ByteArray,181 ourStaticPublicKey: ByteArray,182 send: suspend (ByteArray) -> Unit,183 receive: suspend () -> ByteArray,184): NoiseXXSession {185 var h = initHash()186 var ck = h.copyOf()187188 val msg1 = receive()189 require(msg1.size >= 32) { "Noise XX: msg1 too short" }190 val remoteEphemeral = msg1.copyOfRange(0, 32)191 h = mixHash(h, remoteEphemeral)192193 val e = generateKeyPair()194 h = mixHash(h, e.publicKey)195 val ee = sharedKey(e.secretKey, remoteEphemeral)196 val (ck1, k1) = hkdf2(ck, ee)197 ck = ck1198199 val encryptedOurStatic = chachaSeal(k1, nonceBytes(0L), ourStaticPublicKey, h)200 h = mixHash(h, encryptedOurStatic)201202 val es = sharedKey(ourStaticPrivateKey, remoteEphemeral)203 val (ck2, k2) = hkdf2(ck, es)204 ck = ck2205206 val encryptedPayload = chachaSeal(k2, nonceBytes(0L), ByteArray(0), h)207 h = mixHash(h, encryptedPayload)208209 val msg2 = ByteArray(e.publicKey.size + encryptedOurStatic.size + encryptedPayload.size)210 e.publicKey.copyInto(msg2, 0)211 encryptedOurStatic.copyInto(msg2, e.publicKey.size)212 encryptedPayload.copyInto(msg2, e.publicKey.size + encryptedOurStatic.size)213 send(msg2)214215 val msg3 = receive()216 require(msg3.size >= 32 + 16 + 16) { "Noise XX: msg3 too short" }217 val encryptedRemoteStatic = msg3.copyOfRange(0, 32 + 16)218 val encryptedFinalPayload = msg3.copyOfRange(32 + 16, msg3.size)219220 val remoteStaticPlain = chachaOpen(k2, nonceBytes(1L), encryptedRemoteStatic, h)221 ?: throw IllegalStateException("Noise XX: msg3 static auth failed")222 require(remoteStaticPlain.size == 32) { "Noise XX: msg3 static auth failed" }223 h = mixHash(h, encryptedRemoteStatic)224225 val se = sharedKey(e.secretKey, remoteStaticPlain)226 val (ck3, k3) = hkdf2(ck, se)227 ck = ck3228229 val finalPayloadPlain = chachaOpen(k3, nonceBytes(0L), encryptedFinalPayload, h)230 ?: throw IllegalStateException("Noise XX: msg3 final payload auth failed")231 h = mixHash(h, encryptedFinalPayload)232 @Suppress("UNUSED_VARIABLE")233 val _finalPayloadPlain = finalPayloadPlain234235 val (initSend, respSend) = hkdf2(ck, ByteArray(0))236 val sendCipher = respSend237 val recvCipher = initSend238 var sendNonce = 0L239 var recvNonce = 0L240241 return object : NoiseXXSession {242 override fun encrypt(plaintext: ByteArray): ByteArray {243 return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))244 }245246 override fun decrypt(ciphertext: ByteArray): ByteArray {247 return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))248 ?: throw IllegalStateException("Noise XX: decryption failed")249 }250251 override val remoteStaticPublicKey: ByteArray = remoteStaticPlain252 override val handshakeHash: ByteArray = h.copyOf()253 }254}