NoiseNK.kt

7.4 KB · raw

1package com.peachpasswords.sync23import org.bouncycastle.crypto.digests.Blake2sDigest4import org.bouncycastle.crypto.digests.SHA256Digest5import 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 NOISE_NK_PROTOCOL_NAME = "Noise_NK_25519_ChaChaPoly_BLAKE2s"1718interface NoiseNKSession {19    fun encrypt(plaintext: ByteArray): ByteArray20    fun decrypt(ciphertext: ByteArray): ByteArray21    val handshakeHash: ByteArray22}2324private data class NoiseNKKeyPair(25    val publicKey: ByteArray,26    val secretKey: ByteArray,27)2829private fun initHash(): ByteArray {30    val nameBytes = NOISE_NK_PROTOCOL_NAME.encodeToByteArray()31    if (nameBytes.size <= 32) {32        return ByteArray(32).also { nameBytes.copyInto(it) }33    }34    val sha = SHA256Digest()35    sha.update(nameBytes, 0, nameBytes.size)36    val out = ByteArray(32)37    sha.doFinal(out, 0)38    return out39}4041private fun mixHash(h: ByteArray, data: ByteArray): ByteArray {42    val blake = Blake2sDigest(256)43    blake.update(h, 0, h.size)44    blake.update(data, 0, data.size)45    val out = ByteArray(32)46    blake.doFinal(out, 0)47    return out48}4950private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {51    val generator = HKDFBytesGenerator(SHA256Digest())52    generator.init(HKDFParameters(ikm, ck, ByteArray(0)))53    val out = ByteArray(64)54    generator.generateBytes(out, 0, out.size)55    return out.copyOfRange(0, 32) to out.copyOfRange(32, 64)56}5758private fun nonceBytes(n: Long): ByteArray {59    val buf = ByteArray(12)60    ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).putLong(4, n)61    return buf62}6364private fun generateKeyPair(): NoiseNKKeyPair {65    val priv = X25519PrivateKeyParameters(SecureRandom())66    return NoiseNKKeyPair(67        publicKey = priv.generatePublicKey().encoded,68        secretKey = priv.encoded,69    )70}7172private fun sharedKey(privateKey: ByteArray, publicKey: ByteArray): ByteArray {73    val priv = X25519PrivateKeyParameters(privateKey, 0)74    val pub = X25519PublicKeyParameters(publicKey, 0)75    val out = ByteArray(32)76    priv.generateSecret(pub, out, 0)77    return out78}7980private fun chachaSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {81    val cipher = ChaCha20Poly1305()82    cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce, aad))83    val out = ByteArray(cipher.getOutputSize(plaintext.size))84    var len = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)85    len += cipher.doFinal(out, len)86    return out.copyOf(len)87}8889private fun chachaOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray? {90    return try {91        val cipher = ChaCha20Poly1305()92        cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce, aad))93        val out = ByteArray(cipher.getOutputSize(ciphertext.size))94        var len = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)95        len += cipher.doFinal(out, len)96        out.copyOf(len)97    } catch (_: Throwable) {98        null99    }100}101102suspend fun noiseNKInitiator(103    responderStaticPublicKey: ByteArray,104    send: suspend (ByteArray) -> Unit,105    receive: suspend () -> ByteArray,106): NoiseNKSession {107    var h = initHash()108    var ck = h.copyOf()109110    h = mixHash(h, responderStaticPublicKey)111112    val ephemeral = generateKeyPair()113    h = mixHash(h, ephemeral.publicKey)114    val es = sharedKey(ephemeral.secretKey, responderStaticPublicKey)115    val (ck1, k1) = hkdf2(ck, es)116    ck = ck1117118    val cipher1 = ChaCha20Poly1305()119    cipher1.init(true, AEADParameters(KeyParameter(k1), 128, nonceBytes(0L), h))120    val encrypted1 = ByteArray(cipher1.getOutputSize(0))121    cipher1.doFinal(encrypted1, 0)122    h = mixHash(h, encrypted1)123124    val msg1 = ByteArray(32 + encrypted1.size)125    ephemeral.publicKey.copyInto(msg1, 0)126    encrypted1.copyInto(msg1, 32)127    send(msg1)128129    val msg2 = receive()130    require(msg2.size >= 48) { "Noise NK: msg2 too short" }131    val remoteEphemeralPublic = msg2.copyOfRange(0, 32)132    val encrypted2 = msg2.copyOfRange(32, msg2.size)133134    h = mixHash(h, remoteEphemeralPublic)135    val ee = sharedKey(ephemeral.secretKey, remoteEphemeralPublic)136    val (ck2, k2) = hkdf2(ck, ee)137    ck = ck2138139    val decrypted2 = chachaOpen(k2, nonceBytes(0L), encrypted2, h)140    requireNotNull(decrypted2) { "Noise NK: msg2 auth failed — wrong responder key or MITM" }141    h = mixHash(h, encrypted2)142143    val (sendKey, recvKey) = hkdf2(ck, ByteArray(0))144    val sessionHash = h.copyOf()145146    var sendNonce = 0L147    var recvNonce = 0L148149    return object : NoiseNKSession {150        override fun encrypt(plaintext: ByteArray): ByteArray {151            return chachaSeal(sendKey, nonceBytes(sendNonce++), plaintext, ByteArray(0))152        }153154        override fun decrypt(ciphertext: ByteArray): ByteArray {155            return chachaOpen(recvKey, nonceBytes(recvNonce++), ciphertext, ByteArray(0))156                ?: throw IllegalStateException("Noise NK: decryption failed")157        }158159        override val handshakeHash: ByteArray = sessionHash160    }161}162163suspend fun noiseNKResponder(164    ourStaticPrivateKey: ByteArray,165    ourStaticPublicKey: ByteArray,166    send: suspend (ByteArray) -> Unit,167    receive: suspend () -> ByteArray,168): NoiseNKSession {169    var h = initHash()170    var ck = h.copyOf()171172    h = mixHash(h, ourStaticPublicKey)173174    val msg1 = receive()175    require(msg1.size >= 48) { "Noise NK: msg1 too short" }176    val remoteEphemeralPublic = msg1.copyOfRange(0, 32)177    val encrypted1 = msg1.copyOfRange(32, msg1.size)178179    h = mixHash(h, remoteEphemeralPublic)180    val es = sharedKey(ourStaticPrivateKey, remoteEphemeralPublic)181    val (ck1, k1) = hkdf2(ck, es)182    ck = ck1183184    val decrypted1 = chachaOpen(k1, nonceBytes(0L), encrypted1, h)185    requireNotNull(decrypted1) { "Noise NK: msg1 auth failed — wrong static key or MITM" }186    h = mixHash(h, encrypted1)187188    val ephemeral = generateKeyPair()189    h = mixHash(h, ephemeral.publicKey)190    val ee = sharedKey(ephemeral.secretKey, remoteEphemeralPublic)191    val (ck2, k2) = hkdf2(ck, ee)192    ck = ck2193194    val encrypted2 = chachaSeal(k2, nonceBytes(0L), ByteArray(0), h)195    h = mixHash(h, encrypted2)196197    val msg2 = ByteArray(32 + encrypted2.size)198    ephemeral.publicKey.copyInto(msg2, 0)199    encrypted2.copyInto(msg2, 32)200    send(msg2)201202    val (initiatorSendKey, responderSendKey) = hkdf2(ck, ByteArray(0))203    val sessionHash = h.copyOf()204205    var sendNonce = 0L206    var recvNonce = 0L207208    return object : NoiseNKSession {209        override fun encrypt(plaintext: ByteArray): ByteArray {210            return chachaSeal(responderSendKey, nonceBytes(sendNonce++), plaintext, ByteArray(0))211        }212213        override fun decrypt(ciphertext: ByteArray): ByteArray {214            return chachaOpen(initiatorSendKey, nonceBytes(recvNonce++), ciphertext, ByteArray(0))215                ?: throw IllegalStateException("Noise NK: decryption failed")216        }217218        override val handshakeHash: ByteArray = sessionHash219    }220}221222fun derivePairingSAS(handshakeHash: ByteArray): String {223    return SASDerivation.derive(handshakeHash)224}