Clavem

Verify an Ed25519 license token offline in Kotlin

On the JVM, Signature.getInstance("Ed25519") verifies a Clavem token with no library from JDK 15 on. Wrap the 32-byte public key in a fixed header, verify the text "sgt1.<payload>" as received, then check v, pid, valid, exp and refresh_by. Android below API 33 needs BouncyCastle for the one verify call.

The verifier

A Clavem token is sgt1.<payload>.<signature>. The signature is Ed25519 over the ASCII text of the first two parts joined by a dot, exactly as received, and the payload is base64url JSON. The format and each claim are described on offline verification. This is the Kotlin version. One function, ed25519Verify, differs by platform, so it is separate from the rest.

// Token.kt: JDK 15 or later (desktop and server). kotlinx-serialization-json for the claims.
import java.security.GeneralSecurityException
import java.security.KeyFactory
import java.security.MessageDigest
import java.security.Signature
import java.security.spec.X509EncodedKeySpec
import java.util.Base64
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class Claims(
    val v: Int,
    val lid: Long,
    val pid: Long,
    val kh: String,
    val status: String,
    val valid: Boolean,
    val iid: String? = null,
    val fp: String? = null,
    val email: String? = null,
    val iat: Long,
    val exp: Long? = null,
    @SerialName("refresh_by") val refreshBy: Long,
)

private val json = Json { ignoreUnknownKeys = true }
private val base64Url = Base64.getUrlDecoder() // strict about characters, and padding is optional

// The fixed header of an Ed25519 SubjectPublicKeyInfo. The 32 raw key bytes follow it.
private val SPKI_PREFIX = byteArrayOf(0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00)

/** The one line that differs by platform. This version needs JDK 15 or later. */
fun ed25519Verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean {
    val key = KeyFactory.getInstance("Ed25519").generatePublic(X509EncodedKeySpec(SPKI_PREFIX + publicKey))
    return Signature.getInstance("Ed25519").run {
        initVerify(key)
        update(message)
        verify(signature)
    }
}

/** Returns the claims when the signature is valid, otherwise null. */
fun verifyToken(token: String?, publicKey: String): Claims? {
    val parts = token?.split('.') ?: return null
    if (parts.size != 3 || parts[0] != "sgt1") return null
    return try {
        val key = base64Url.decode(publicKey)
        if (key.size != 32) return null
        val signed = "${parts[0]}.${parts[1]}".toByteArray(Charsets.US_ASCII) // the text as received
        if (!ed25519Verify(key, signed, base64Url.decode(parts[2]))) return null
        json.decodeFromString<Claims>(String(base64Url.decode(parts[1]), Charsets.UTF_8))
    } catch (e: GeneralSecurityException) {
        null // bad key, or a signature of the wrong length
    } catch (e: IllegalArgumentException) {
        null // not base64url, or a payload that is not the claims (SerializationException is one)
    }
}

/** The checks your app should make on a verified token. */
fun isLicensed(claims: Claims?, productId: Long, now: Long = System.currentTimeMillis() / 1000): Boolean =
    claims != null &&
        claims.v == 1 &&
        claims.pid == productId &&
        claims.valid &&
        (claims.exp == null || claims.exp > now) &&
        claims.refreshBy > now

/** Optional: confirms the token was issued for the key the customer typed. */
fun matchesKey(claims: Claims, licenseKey: String): Boolean {
    val trimmed = licenseKey.trim()
    val native = Regex("^[0-9A-Za-z]{5}(-[0-9A-Za-z]{5}){4}$").matches(trimmed)
    val normalized = if (native) {
        trimmed.uppercase().replace(Regex("[IL]"), "1").replace('O', '0').replace('U', 'V') // uppercase() ignores the locale
    } else {
        trimmed.lowercase()
    }
    val digest = MessageDigest.getInstance("SHA-256").digest(normalized.toByteArray())
    return digest.joinToString("") { "%02x".format(it) }.take(16) == claims.kh
}

Keep the public key from your product page in the build. On Android, a buildConfigField keeps it out of the source files you edit by hand:

// app/build.gradle.kts, inside android { defaultConfig { ... } }
buildConfigField("String", "CLAVEM_PUBLIC_KEY", "\"YOUR_PUBLIC_KEY\"")

Which Ed25519 to call

Where it runs Route Note
Desktop JVM, server, Compose Desktop The JDK, as above Needs JDK 15 or later, which is when the JDK added EdDSA. No dependency.
Android, API 33 and later The same JDK-style call The Android reference lists the Ed25519 Signature algorithm from API 33.
Android below API 33, or one path for everything BouncyCastle’s lightweight API Works on every level.

The BouncyCastle version replaces the function and nothing else. It uses the library’s own classes and not a registered provider, so it does not depend on what the device ships:

// Dependency: org.bouncycastle:bcprov-jdk18on
import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters
import org.bouncycastle.crypto.signers.Ed25519Signer

fun ed25519Verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean {
    val signer = Ed25519Signer()
    signer.init(false, Ed25519PublicKeyParameters(publicKey, 0))
    signer.update(message, 0, message.size)
    return signer.verifySignature(signature)
}

Results

The JDK version ran on a JVM 17 with Kotlin 2.4.21. The tokens were signed with a throwaway Ed25519 key in the documented format, with PRODUCT_ID 75:

Token Signature Licensed
Fresh and active valid yes
pid edited after signing rejected no
refresh_by six days ago valid no
Expired license, valid: false valid no
Product 99, v: 2, or exp in the past valid no
Signed by another key pair rejected no
Null token, two parts, prefix sgt2, garbage or short public key null no

A signature with = or two junk characters appended, or four characters cut off, returned null as well. The Java decoder is strict about characters and does not forgive padding that Clavem never sends. matchesKey returned true for the demo key in capitals and in lowercase with spaces. The computed hash is 7e0e4148136b6dae, the kh the live demo license carries. We could not verify that license’s real signature, because the demo product’s public key is not available to us.

Two Kotlin details

  • Turkish locale. In the normalization for matchesKey, "i".uppercase(Locale.forLanguageTag("tr")) is İ, not I. The plain uppercase() ignores the device locale and returned I. The older toUpperCase() follows the default locale, which is how a key typed on a Turkish phone could stop matching its kh.
  • Smart casts. claims.exp > now compiles after the null check because exp is a val in the same module. If you move Claims to another module, copy it to a local first.

Clock and storage

The token sits in the license file from the validation page. System.currentTimeMillis() is the wall clock, which a customer can move back to stretch the 14 days. Store the highest iat you have seen and treat an earlier clock as stale. SystemClock.elapsedRealtime() cannot replace it, because it restarts at every boot. The other limits, including how long a disabled license keeps verifying, are under what a token cannot tell you.

Doing this with Clavem

Each Clavem product has its own Ed25519 key pair, and the public half is on the product page. The token decoder shows the claims of any token you paste.

Questions

Does Android have built-in Ed25519 signature verification?

The Android reference lists an Ed25519 Signature algorithm from API level 33. For an app whose minSdk is lower, put the one verify function on a library such as BouncyCastle, so a single code path covers every device.

Why do the claims use Long for iat, exp and refresh_by?

They are Unix seconds. Today's values, around 1.8 billion, still fit in an Int, but only until 2038, and the JSON numbers are not limited to 32 bits. Long avoids a cutoff you would have to remember.

Sources

  1. Android developers, java.security.Signature algorithms and API levels (checked November 2026)
  2. OpenJDK, JEP 339 Edwards-Curve Digital Signature Algorithm (checked November 2026)