# CybSin in Kotlin (Android) — OkHttp + BouncyCastle (X25519) + javax.crypto (ChaCha20-Poly1305)

```kotlin
// build.gradle: implementation("com.squareup.okhttp3:okhttp:4.12.0"); implementation("org.bouncycastle:bcprov-jdk18on:1.78")
import android.content.Context
import android.os.Build
import android.provider.Settings
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okio.ByteString
import okio.ByteString.Companion.toByteString
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.json.JSONObject
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.util.concurrent.LinkedBlockingQueue

object CybSinConfig { var server = "https://cybsin.com"; const val APP_KEY = "cs_app_REPLACE_ME" }

fun deviceIdentity(ctx: Context) = JSONObject().apply {
    put("name", "${Build.MANUFACTURER} ${Build.MODEL}"); put("platform", "android"); put("model", Build.MODEL)
    put("os_version", Build.VERSION.RELEASE); put("android_id", Settings.Secure.getString(ctx.contentResolver, Settings.Secure.ANDROID_ID))
    put("bundle_id", ctx.packageName); put("app_version", ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: "")
    put("locale", java.util.Locale.getDefault().toLanguageTag())
}

class CybSinClient(private val ctx: Context) {
    private val http = OkHttpClient(); var token: String? = null; var deviceId: Int? = null
    private fun post(path: String, body: JSONObject, auth: Boolean = false): JSONObject {
        val b = Request.Builder().url(CybSinConfig.server + path).header("X-App-Key", CybSinConfig.APP_KEY)
            .post(body.toString().toRequestBody("application/json".toMediaType()))
        if (auth) b.header("Authorization", "Bearer $token")
        http.newCall(b.build()).execute().use { r ->
            val j = JSONObject(r.body?.string() ?: "{}")
            if (r.code == 402) throw IllegalStateException("payment_required: ${j.opt("detail")}")   // show a human message
            if (!r.isSuccessful) throw IllegalStateException("HTTP ${r.code}: $j")
            return j
        }
    }
    fun signIn(email: String, password: String, register: Boolean) {
        val r = post(if (register) "/api/v1/register" else "/api/v1/login",
            JSONObject().put("email", email).put("password", password).put("device", deviceIdentity(ctx)))
        token = r.getString("token"); deviceId = r.optInt("device_id")
    }
    fun pairNew(): Triple<String, String, String> =
        post("/api/v1/pair/new", JSONObject().put("device_id", deviceId), true).let { Triple(it.getString("code"), it.getString("session_id"), it.optString("qr")) }
    fun pairJoin(code: String): String = post("/api/v1/pair/join", JSONObject().put("code", code).put("device_id", deviceId), true).getString("session_id")

    fun connect(session: String, host: Boolean, code: String): Tunnel {
        val url = CybSinConfig.server.replaceFirst("http", "ws") +
            "/ws/relay/$session?token=$token&role=${if (host) "host" else "guest"}&app_key=${CybSinConfig.APP_KEY}&device_id=${deviceId ?: 0}"
        val inbox = LinkedBlockingQueue<Any>()           // String control frames or ByteString binary frames
        val ws = http.newWebSocket(Request.Builder().url(url).build(), object : WebSocketListener() {
            override fun onMessage(webSocket: WebSocket, text: String) { inbox.put(text) }
            override fun onMessage(webSocket: WebSocket, bytes: ByteString) { inbox.put(bytes) }
            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { inbox.put("""{"t":"peer_left"}""") }
            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { inbox.put("""{"t":"peer_left","error":"${t.message}"}""") }
        })
        while (true) {                                    // wait for joined
            val m = inbox.take()
            if (m is String) { val j = JSONObject(m); when { j.optString("t") == "joined" -> break
                j.optString("t") == "expired" || j.has("code") -> throw IllegalStateException(m) } }
        }
        return Tunnel.handshake(ws, inbox, host, code)
    }
}

class Tunnel private constructor(private val ws: WebSocket, private val inbox: LinkedBlockingQueue<Any>, private val key: ByteArray,
                                 private val dirMe: Byte, private val dirThem: Byte, val sas: String) {
    private var tx = 0L; private var rx = 0L
    companion object {
        fun handshake(ws: WebSocket, inbox: LinkedBlockingQueue<Any>, host: Boolean, code: String): Tunnel {
            val gen = X25519KeyPairGenerator().apply { init(X25519KeyGenerationParameters(SecureRandom())) }
            val kp = gen.generateKeyPair()
            val mine = (kp.public as X25519PublicKeyParameters).encoded
            ws.send(mine.toByteString())
            var theirs: ByteArray? = null
            while (theirs == null) { val m = inbox.take(); if (m is ByteString && m.size == 32) theirs = m.toByteArray() }
            val shared = ByteArray(32).also { X25519Agreement().apply { init(kp.private as X25519PrivateKeyParameters) }.calculateAgreement(X25519PublicKeyParameters(theirs, 0), it, 0) }
            val key = hkdfSha256(shared, code.toByteArray(), "cybsin-v1".toByteArray(), 32)
            val (hp, gp) = if (host) mine to theirs else theirs to mine
            val fp = MessageDigest.getInstance("SHA-256").digest(hp + gp)
            val sas = "%02X%02X · %02X%02X".format(fp[0], fp[1], fp[2], fp[3])
            return Tunnel(ws, inbox, key, if (host) 1 else 2, if (host) 2 else 1, sas)
        }
        private fun hkdfSha256(ikm: ByteArray, salt: ByteArray, info: ByteArray, len: Int): ByteArray {
            val mac = Mac.getInstance("HmacSHA256"); mac.init(SecretKeySpec(salt, "HmacSHA256")); val prk = mac.doFinal(ikm)
            mac.init(SecretKeySpec(prk, "HmacSHA256")); var t = ByteArray(0); val out = ByteArray(len); var pos = 0; var i = 1
            while (pos < len) { mac.update(t); mac.update(info); mac.update(i.toByte()); t = mac.doFinal()
                val n = minOf(t.size, len - pos); System.arraycopy(t, 0, out, pos, n); pos += n; i++ }
            return out
        }
    }
    private fun nonce(dir: Byte, counter: Long) = ByteBuffer.allocate(12).put(dir).put(0).put(0).put(0).putLong(counter).array()
    private fun cipher(mode: Int, dir: Byte, counter: Long): Cipher =
        Cipher.getInstance("ChaCha20-Poly1305").apply { init(mode, SecretKeySpec(key, "ChaCha20"), IvParameterSpec(nonce(dir, counter))) }  // API 28+
    fun send(plaintext: ByteArray) { ws.send(cipher(Cipher.ENCRYPT_MODE, dirMe, tx++).doFinal(plaintext).toByteString()) }  // ciphertext||tag
    /** payload bytes, or null when the peer left; throws on decryption failure (fatal). */
    fun receive(): ByteArray? {
        while (true) {
            val m = inbox.take()
            if (m is String) { if (m.contains("peer_left") || m.contains("expired")) return null; continue }
            return cipher(Cipher.DECRYPT_MODE, dirThem, rx++).doFinal((m as ByteString).toByteArray())
        }
    }
    fun close() = ws.close(1000, null)
}
```

Notes
- `ChaCha20-Poly1305` via `javax.crypto` needs API 28+; below that use BouncyCastle's `ChaCha20Poly1305` engine with the same nonce layout.
- Android does not expose the MAC address; `android_id` + model is the identity. Store the token in EncryptedSharedPreferences / Keystore.
- Scan the pairing QR (`cybsin://pair?server=…&code=…&app=…`) with ML Kit or ZXing and pre-fill the code.
