Clavem

Verify a Clavem license token offline in Java

Java 15 and later verify Ed25519 with no library. Wrap the 32-byte public key in the fixed X.509 SubjectPublicKeyInfo prefix, load it with KeyFactory, check the signature over "sgt1.<payload>" with Signature.getInstance("Ed25519"), then read the claims with Jackson.

The token format and the claim checks are in the offline verification reference, which covers other languages. This page is the Java version. It reports why a token was refused, takes the clock as a parameter so tests need no timers, and shows the one step that trips people up: loading a raw Ed25519 key. The call that fetches the token is in license key validation in Java.

The key-wrapping step was checked separately. The 44-byte DER built from the prefix and a raw key imported correctly in another runtime, verified a token signature, and exported back to identical bytes. The check logic was run in Swift, Rust, Python, C++ and Node against the same test tokens.

The verifier

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.function.Supplier;

public final class TokenVerifier {
    public enum Check { OK, MALFORMED, BAD_SIGNATURE, WRONG_PRODUCT, NOT_VALID, EXPIRED, STALE, CLOCK_SET_BACK }

    // The DER header of an Ed25519 SubjectPublicKeyInfo. Append the 32 raw key bytes.
    private static final byte[] SPKI_PREFIX = HexFormat.of().parseHex("302a300506032b6570032100");

    private final PublicKey key;
    private final long productId;
    private final Supplier<Instant> now;
    private final ObjectMapper json = new ObjectMapper();

    /** publicKey: 32 raw bytes, base64url, from your product page. Throws when it is not a key. */
    public TokenVerifier(String publicKey, long productId, Supplier<Instant> now) throws GeneralSecurityException {
        byte[] raw = Base64.getUrlDecoder().decode(publicKey.trim());
        if (raw.length != 32) throw new IllegalArgumentException("The public key must be 32 bytes, base64url.");
        byte[] der = new byte[SPKI_PREFIX.length + raw.length];
        System.arraycopy(SPKI_PREFIX, 0, der, 0, SPKI_PREFIX.length);
        System.arraycopy(raw, 0, der, SPKI_PREFIX.length, raw.length);
        this.key = KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der));
        this.productId = productId;
        this.now = now;
    }

    public TokenVerifier(String publicKey, long productId) throws GeneralSecurityException {
        this(publicKey, productId, Instant::now);
    }

    /** Returns the claims when the signature is good, otherwise null and the reason in `why[0]`. */
    JsonNode claims(String token, Check[] why) {
        String[] parts = token.split("\\.", -1);
        if (parts.length != 3 || !parts[0].equals("sgt1")) { why[0] = Check.MALFORMED; return null; }
        byte[] signature, payload;
        try {
            signature = Base64.getUrlDecoder().decode(parts[2]);
            payload = Base64.getUrlDecoder().decode(parts[1]);
        } catch (IllegalArgumentException e) { why[0] = Check.MALFORMED; return null; }
        if (signature.length != 64) { why[0] = Check.MALFORMED; return null; }   // verify() throws on a wrong length

        try {
            Signature verifier = Signature.getInstance("Ed25519");
            verifier.initVerify(key);
            verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII));   // the text exactly as received
            if (!verifier.verify(signature)) { why[0] = Check.BAD_SIGNATURE; return null; }
            JsonNode claims = json.readTree(payload);
            if (!claims.isObject()) { why[0] = Check.MALFORMED; return null; }
            why[0] = Check.OK;
            return claims;
        } catch (GeneralSecurityException | IOException e) {
            why[0] = Check.MALFORMED;
            return null;
        }
    }

    /** highestIat is the largest iat verified before. */
    public Check check(String token, long highestIat) {
        Check[] why = new Check[1];
        JsonNode c = claims(token, why);
        if (c == null) return why[0];
        long t = now.get().getEpochSecond();
        if (c.path("v").asInt(0) != 1) return Check.MALFORMED;
        if (c.path("pid").asLong(-1) != productId) return Check.WRONG_PRODUCT;
        if (!c.path("valid").isBoolean() || !c.path("valid").asBoolean()) return Check.NOT_VALID;
        if (c.has("exp") && c.path("exp").asLong(0) <= t) return Check.EXPIRED;
        if (t < highestIat) return Check.CLOCK_SET_BACK;
        if (c.path("refresh_by").asLong(0) <= t) return Check.STALE;
        return Check.OK;
    }
}

Only OK should turn the paid features on, and STALE means validate online once. Build one verifier at startup. The constructor throws for a bad key or an unsupported runtime, so a mistake shows up in development.

Why the prefix

KeyFactory for Ed25519 reads a public key from the X.509 SubjectPublicKeyInfo structure. For Ed25519 that structure is always 44 bytes: the 12-byte header 302a300506032b6570032100, then the 32 raw key bytes. The product page gives you only the 32 bytes, so the constructor adds the header. Without it you would build an EdECPoint by hand, which means reversing the bytes and carrying the sign bit of x.

What the checks give

These results come from the same logic run on test tokens signed with a throwaway key in the documented sgt1 format, in the Swift, Rust, Python, C++ and Node versions of this guide. The Java code should return the same:

Token Result
Fresh OK
exp in 30 days OK
exp a minute ago EXPIRED
refresh_by 6 days ago STALE
Issued for an expired license (valid: false) NOT_VALID
Another product’s pid WRONG_PRODUCT
v is 2 MALFORMED
Payload edited to a far-off exp, old signature BAD_SIGNATURE
Signed by another key BAD_SIGNATURE
The live demo token, with a different public key BAD_SIGNATURE
Two or four parts, sgt2 prefix, plain text MALFORMED
Fresh token, 15 days later STALE
Fresh token, clock behind a token already seen CLOCK_SET_BACK

The live demo token is real and decodes, but Clavem signed it with its own key, so a verifier built with any other public key has to refuse it. Pass a fixed Supplier<Instant> in a JUnit parameterized test, and the 15-days-later row needs no waiting.

Key, clock and storage

kh ties a token to the key the customer typed: the first 16 hex characters of the SHA-256 of the normalized key. A Clavem-format key is uppercased with I and L read as 1, O as 0 and U as V. Any other key is lowercased. Use MessageDigest.getInstance("SHA-256") and HexFormat.of().formatHex(digest).substring(0, 16).

For the clock, keep the highest iat you have verified in the same keyring entry as the license, and pass it as highestIat. Raise it only after check returned OK. A user who deletes the entry starts over, and nothing offline can prevent that. The guard stops the casual date change. A token is signed, not secret, so a file under the user’s application data directory is enough. The payload includes the buyer’s email in readable form, so keep tokens out of logs.

Traps in Java

  • Java 15 or later. On Java 11 the Signature.getInstance("Ed25519") call throws NoSuchAlgorithmException. Set --release 17 in your build so the compiler tells you.
  • verify throws on a signature of the wrong length. The code checks for 64 bytes first.
  • Base64.getDecoder() is the wrong decoder. It uses the standard alphabet. Use getUrlDecoder().
  • Do not catch Exception broadly around verify. A SignatureException for a bad length and false for a bad signature are different outcomes in your logs.
  • Trimmed runtimes. If you build a custom runtime with jlink, make sure it includes the module that provides the SunEC algorithms (jdk.crypto.ec in the JDK 15 to 21 line). Without it the Signature.getInstance lookup fails. Run your jlink image once and verify a token in it.

Doing this with Clavem

Each product has its own key pair. The public half is on the product page and in GET /v1/admin/products, and every activate and validate response carries a token signed with the private half. See the API reference for the endpoints.

Questions

Does Java have Ed25519 built in?

Yes, since Java 15, through JEP 339. Use Signature.getInstance with the name Ed25519. On Java 11 and earlier you need a library such as BouncyCastle.

Why do I need to add a prefix to the public key?

Java's KeyFactory reads Ed25519 public keys from X.509 SubjectPublicKeyInfo DER, not from raw bytes. The prefix 302a300506032b6570032100 followed by the 32 raw bytes is the standard encoding for an Ed25519 key.

Does Base64.getUrlDecoder accept unpadded input?

Yes. The Java decoder accepts input without the equals padding, and it throws IllegalArgumentException on a character outside the alphabet. That is stricter than many languages' decoders, which is what you want here.

Sources

  1. JEP 339, Edwards-Curve Digital Signature Algorithm (EdDSA) (checked November 2026)