// Keyfern client for Kotlin and Java: Android (API 26+) and any JVM 11+. One file, no dependencies. // // val kf = Keyfern("prod_xxx", "", storage = FileStorage(File(filesDir, "keyfern.license"))) // val lic = kf.activateOrCached("ABCDE-FGHIJ-KLMNO-PQRST", Keyfern.machineId()) // blocking: call it off the main thread // if (5 in lic.features) { ... } // // Every answer is Ed25519-signed; only answers that verify with the embedded PUBLIC key are trusted, and the // nonce must match the one we sent (no replay). With `storage` the last signed answer is kept, so the app runs // offline until `leaseUntil`; setting the clock back is detected. The cache needs no encryption: editing it // breaks the signature. // // Ed25519 comes from java.security on JVM 15+ and Android 13 (API 33)+. For Android 8-12 (API 26-32) pass // `verifier` backed by BouncyCastle or Tink: see https://keyfern.com/docs/android package com.keyfern import java.io.File import java.net.HttpURLConnection import java.net.URI import java.nio.file.Files import java.nio.file.StandardCopyOption import java.security.KeyFactory import java.security.MessageDigest import java.security.Signature import java.security.spec.X509EncodedKeySpec import java.util.Base64 import java.util.UUID open class KeyfernException(val code: String, message: String? = null) : Exception(message ?: code) class KeyfernNetworkException(message: String?) : Exception(message) /** Where the last signed license is kept for offline use. */ interface LicenseStorage { fun get(): String? fun set(value: String) fun remove() } /** A file (written atomically). On Android use File(context.filesDir, "keyfern.license"). */ class FileStorage(private val file: File) : LicenseStorage { override fun get(): String? = if (file.isFile) file.readText() else null override fun set(value: String) { val tmp = File(file.path + ".tmp") tmp.writeText(value) Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) } override fun remove() { file.delete() } } /** The signed envelope {payload, sig}: store it and pass it to checkCached() later. */ data class SignedLicense(val payload: String, val sig: String) /** The verified license. `raw` holds every field of the signed payload. */ class License(val raw: Map, val signed: SignedLicense) { private fun long(k: String) = (raw[k] as Number?)?.toLong() private fun map(k: String) = raw[k] as? Map<*, *> val product: String get() = raw["product"] as String val key: String get() = raw["key"] as String val machine: String? get() = raw["machine"] as String? val nonce: String? get() = raw["nonce"] as String? /** "active", "expired" or "blocked". */ val status: String get() = raw["status"] as String /** Server time of the answer (unix seconds). */ val iat: Long get() = long("iat") ?: 0 /** Unix seconds, null = never expires. */ val expires: Long? get() = long("expires") /** Offline use is allowed until this moment (unix seconds, null = unlimited). */ val leaseUntil: Long? get() = long("lease_until") val features: List get() = (raw["features"] as? List<*>)?.map { (it as Number).toInt() } ?: emptyList() val maxMachines: Int get() = (raw["max_machines"] as Number?)?.toInt() ?: 0 val machinesUsed: Int get() = (raw["machines_used"] as Number?)?.toInt() ?: 0 val customerName: String? get() = map("customer")?.get("name") as String? val customerEmail: String? get() = map("customer")?.get("email") as String? val meta: Map<*, *> get() = map("meta") ?: emptyMap() fun has(feature: Int) = feature in features override fun toString() = "License($key $status features=$features expires=$expires)" } class Keyfern( val product: String, publicKey: String, url: String = "https://keyfern.com", val storage: LicenseStorage? = null, val timeoutMs: Int = 15000, /** Ed25519 check (publicKey, signature, message) for Android API 26-32. Default: java.security. */ verifier: ((ByteArray, ByteArray, ByteArray) -> Boolean)? = null, ) { private val base = url.trimEnd('/') private val pub = b64d(publicKey) private val verifyFn = verifier ?: { p, s, m -> jdkVerify(p, s, m) } private fun post(path: String, body: Map): Map { var code = 0 val text: String val c = URI(base + path).toURL().openConnection() as HttpURLConnection try { c.requestMethod = "POST"; c.connectTimeout = timeoutMs; c.readTimeout = timeoutMs; c.doOutput = true c.setRequestProperty("Content-Type", "application/json") c.outputStream.use { it.write(Json.write(body).toByteArray()) } code = c.responseCode text = (if (code < 400) c.inputStream else c.errorStream)?.bufferedReader()?.use { it.readText() } ?: "" } catch (e: java.io.IOException) { throw KeyfernNetworkException(e.message) } finally { c.disconnect() } @Suppress("UNCHECKED_CAST") val j = try { Json.parse(text) as Map } catch (e: Exception) { throw KeyfernNetworkException("Unreadable answer (HTTP $code)") } if (code >= 500 || code == 429) throw KeyfernNetworkException(j["message"] as? String ?: "HTTP $code") if (code >= 400) throw KeyfernException(j["error"] as? String ?: "error", j["message"] as? String) return j } /** Verify a {payload, sig} answer. Throws KeyfernException on any mismatch. */ fun verify(signed: SignedLicense, nonce: String? = null): License { val bytes = try { b64d(signed.payload) } catch (e: IllegalArgumentException) { null } val ok = bytes != null && try { verifyFn(pub, b64d(signed.sig), bytes) } catch (e: Exception) { false } if (!ok) throw KeyfernException("bad_signature", "License answer failed signature verification") @Suppress("UNCHECKED_CAST") val p = Json.parse(String(bytes, Charsets.UTF_8)) as Map if (p["product"] != product) throw KeyfernException("bad_signature", "License answer is for another product") if (nonce != null && p["nonce"] != nonce) throw KeyfernException("replay", "License answer does not match this request") return License(p, signed) } private fun call(path: String, extra: Map): License { val nonce = UUID.randomUUID().toString() val r = post(path, mapOf("product" to product, "nonce" to nonce) + extra) return verify(SignedLicense(r["payload"] as String, r["sig"] as String), nonce) } /** Registers this machine. Throws unless the license is active; saves it to `storage`. */ fun activate(key: String, machine: String, name: String? = null): License { val lic = call("/v1/activate", mapOf("key" to key, "machine" to machine, "name" to name)) if (lic.status != "active") throw KeyfernException(lic.status, "License is ${lic.status}") storage?.set(Json.write(mapOf("resp" to mapOf("payload" to lic.signed.payload, "sig" to lic.signed.sig), "machine" to machine, "last_seen" to now()))) return lic } /** Read-only info (works for expired keys too, e.g. to show a Renew button). */ fun validate(key: String, machine: String? = null) = call("/v1/validate", mapOf("key" to key, "machine" to machine)) fun deactivate(key: String, machine: String) { post("/v1/deactivate", mapOf("product" to product, "key" to key, "machine" to machine)) } fun trial(machine: String) = call("/v1/trial", mapOf("machine" to machine)) /** Check a license cached earlier without the network: signature, machine, clock, expiry, lease. */ fun checkCached(signed: SignedLicense, machine: String? = null, lastSeen: Double = 0.0): License { val p = verify(signed) val t = now() if (machine != null && p.machine != machine) throw KeyfernException("wrong_machine", "Cached license belongs to another machine") if (t < maxOf(lastSeen, p.iat.toDouble()) - 3600) throw KeyfernException("clock_rollback", "System clock was set back") // 1 h tolerance p.expires?.let { if (it <= t) throw KeyfernException("expired") } p.leaseUntil?.let { if (it <= t) throw KeyfernException("lease_expired", "Connect to the internet once to refresh the license") } return p } /** The license kept in `storage`, checked offline. Throws KeyfernException("no_cache") when nothing is stored. */ fun cached(machine: String? = null): License { val d = try { storage?.get()?.let { Json.parse(it) } as? Map<*, *> } catch (e: Exception) { null } val r = d?.get("resp") as? Map<*, *> val payload = r?.get("payload") as? String val sig = r?.get("sig") as? String if (payload == null || sig == null) throw KeyfernException("no_cache", "No cached license") val lastSeen = (d["last_seen"] as? Number)?.toDouble() ?: 0.0 val lic = checkCached(SignedLicense(payload, sig), machine, lastSeen) storage!!.set(Json.write(mapOf("resp" to mapOf("payload" to payload, "sig" to sig), "machine" to d["machine"], "last_seen" to maxOf(lastSeen, now())))) return lic } /** Normal start-up call: online activation when possible, the cached license when offline. */ fun activateOrCached(key: String, machine: String, name: String? = null): License = try { activate(key, machine, name) } catch (e: KeyfernNetworkException) { cached(machine) } catch (e: KeyfernException) { if (e.code in setOf("blocked", "expired", "invalid_key", "machine_limit")) storage?.remove() throw e } companion object { private val SPKI = byteArrayOf(0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00) private fun now() = System.currentTimeMillis() / 1000.0 private fun b64d(s: String): ByteArray = Base64.getUrlDecoder().decode(s.trimEnd('=')) private fun jdkVerify(pub: ByteArray, sig: ByteArray, msg: ByteArray): Boolean { val k = KeyFactory.getInstance("Ed25519").generatePublic(X509EncodedKeySpec(SPKI + pub)) return Signature.getInstance("Ed25519").run { initVerify(k); update(msg); verify(sig) } } /** Desktop JVM: stable hashed id of this computer (same value as the Python and JS SDKs). Not for Android. */ fun machineId(salt: String = "keyfern"): String { val os = System.getProperty("os.name").lowercase() var raw = try { when { os.startsWith("windows") -> Regex("MachineGuid\\s+REG_SZ\\s+(\\S+)").find(exec("reg", "query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid", "/reg:64"))?.groupValues?.get(1) os.contains("mac") -> Regex("\"IOPlatformUUID\" = \"([^\"]+)\"").find(exec("ioreg", "-rd1", "-c", "IOPlatformExpertDevice"))?.groupValues?.get(1) else -> listOf("/etc/machine-id", "/var/lib/dbus/machine-id").map(::File).firstOrNull { it.isFile }?.readText()?.trim() } } catch (e: Exception) { null } if (raw.isNullOrEmpty()) raw = java.net.InetAddress.getLocalHost().hostName + java.net.NetworkInterface.networkInterfaces().toList() .mapNotNull { it.hardwareAddress }.firstOrNull { b -> b.any { it.toInt() != 0 } }?.joinToString(":") { "%02x".format(it) } return MessageDigest.getInstance("SHA-256").digest("$salt|$raw".toByteArray()).joinToString("") { "%02x".format(it) }.take(32) } private fun exec(vararg cmd: String) = ProcessBuilder(*cmd).redirectErrorStream(true).start().inputStream.bufferedReader().use { it.readText() } /** A random id created on first use and kept in `file`: on Android, File(context.filesDir, "keyfern.id"). */ fun installId(file: File): String { file.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() }?.let { return it } return UUID.randomUUID().toString().also { file.writeText(it) } } } } /** Minimal JSON reader/writer, enough for Keyfern answers (keeps the SDK free of dependencies). */ internal object Json { fun write(v: Any?): String = when (v) { null -> "null" is String -> buildString { append('"') for (ch in v) when { ch == '"' -> append("\\\""); ch == '\\' -> append("\\\\") ch < ' ' -> append("\\u%04x".format(ch.code)) else -> append(ch) } append('"') } is Number, is Boolean -> v.toString() is Map<*, *> -> v.entries.joinToString(",", "{", "}") { write(it.key.toString()) + ":" + write(it.value) } is List<*> -> v.joinToString(",", "[", "]") { write(it) } else -> write(v.toString()) } fun parse(s: String): Any? = Reader(s).run { val v = value(); ws(); require(i == s.length) { "trailing data" }; v } private class Reader(val s: String) { var i = 0 fun ws() { while (i < s.length && s[i] in " \t\r\n") i++ } fun value(): Any? { ws() require(i < s.length) { "unexpected end" } return when (val c = s[i]) { '{' -> { i++; val m = LinkedHashMap(); ws() if (s[i] == '}') { i++; return m } while (true) { ws(); val k = str(); ws(); expect(':'); m[k] = value(); ws(); if (s[i++] == '}') return m; require(s[i - 1] == ',') { "bad object" } } } '[' -> { i++; val l = ArrayList(); ws() if (s[i] == ']') { i++; return l } while (true) { l.add(value()); ws(); if (s[i++] == ']') return l; require(s[i - 1] == ',') { "bad array" } } } '"' -> str() 't' -> word("true", true) 'f' -> word("false", false) 'n' -> word("null", null) else -> { require(c == '-' || c.isDigit()) { "bad value at $i" } val st = i while (i < s.length && s[i] in "+-.eE0123456789") i++ val t = s.substring(st, i) if (t.any { it in ".eE" }) t.toDouble() else t.toLong() } } } fun expect(c: Char) { require(s[i] == c) { "expected $c at $i" }; i++ } fun word(w: String, v: Any?): Any? { require(s.startsWith(w, i)) { "bad value at $i" }; i += w.length; return v } fun str(): String { expect('"') val b = StringBuilder() while (true) { val c = s[i++] when (c) { '"' -> return b.toString() '\\' -> when (val e = s[i++]) { 'u' -> { b.append(s.substring(i, i + 4).toInt(16).toChar()); i += 4 } 'n' -> b.append('\n'); 't' -> b.append('\t'); 'r' -> b.append('\r') 'b' -> b.append('\b'); 'f' -> b.append('\u000c') else -> b.append(e) } else -> b.append(c) } } } } }