Clavem

Verify a Clavem license token offline in Rust

Split the token on dots, decode the three parts with base64's URL_SAFE_NO_PAD engine, check the Ed25519 signature over the text "sgt1.<payload>" with VerifyingKey::verify_strict, then deserialize the claims and apply the documented checks. It needs no network.

Offline verification describes the token and shows a short Rust version. This page is the version you can ship: it says why a token was refused, takes the clock as an argument so tests do not wait two weeks, and guards against a clock set back. The online call that fetches the token is in license key validation in Rust.

ed25519-dalek = "2"   # tested with 2.2
base64 = "0.22"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"

Verify and check

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Claims {
    pub v: u8, pub lid: u64, pub pid: u64,
    pub kh: String, pub status: String, pub valid: bool,
    pub iid: Option<String>, pub fp: Option<String>, pub email: Option<String>,
    pub iat: i64, pub exp: Option<i64>, pub refresh_by: i64,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Check { Ok, Malformed, BadSignature, WrongProduct, NotValid, Expired, Stale, ClockSetBack }

pub struct Verifier { key: VerifyingKey, product_id: u64 }

impl Verifier {
    /// `public_key`: 32 raw bytes, base64url, from your product page.
    pub fn new(public_key: &str, product_id: u64) -> Option<Self> {
        let bytes: [u8; 32] = URL_SAFE_NO_PAD.decode(public_key.trim()).ok()?.try_into().ok()?;
        Some(Self { key: VerifyingKey::from_bytes(&bytes).ok()?, product_id })
    }

    pub fn claims(&self, token: &str) -> Result<Claims, Check> {
        let mut parts = token.split('.');
        let (Some(prefix), Some(body), Some(sig), None) = (parts.next(), parts.next(), parts.next(), parts.next())
            else { return Err(Check::Malformed) };
        if prefix != "sgt1" { return Err(Check::Malformed); }
        let sig: [u8; 64] = URL_SAFE_NO_PAD.decode(sig).ok().and_then(|b| b.try_into().ok()).ok_or(Check::Malformed)?;
        let payload = URL_SAFE_NO_PAD.decode(body).map_err(|_| Check::Malformed)?;
        self.key
            .verify_strict(format!("{prefix}.{body}").as_bytes(), &Signature::from_bytes(&sig))
            .map_err(|_| Check::BadSignature)?;
        serde_json::from_slice(&payload).map_err(|_| Check::Malformed)
    }

    /// `now` and `highest_iat` are Unix seconds.
    pub fn check(&self, token: &str, now: i64, highest_iat: i64) -> Check {
        let c = match self.claims(token) { Ok(c) => c, Err(why) => return why };
        if c.v != 1 { Check::Malformed }
        else if c.pid != self.product_id { Check::WrongProduct }
        else if !c.valid { Check::NotValid }
        else if c.exp.is_some_and(|exp| exp <= now) { Check::Expired }
        else if now < highest_iat { Check::ClockSetBack }
        else if c.refresh_by <= now { Check::Stale }
        else { Check::Ok }
    }
}

Only Check::Ok turns the paid features on. Stale means validate online once. The other variants are for your log and your message to the customer.

Test results

The tokens were signed with a throwaway key in the documented sgt1 format, and the verifier held its public half. Output of the code above on Rust 1.99:

Token Result
Fresh Ok
exp in 30 days Ok
exp a minute ago Expired
refresh_by 6 days ago Stale
valid: false (issued for an expired license) NotValid
Another product’s pid WrongProduct
v is 2 Malformed
Payload edited to a far-off exp, old signature BadSignature
Signed by another key BadSignature
The live demo token BadSignature
Two or four parts, sgt2 prefix, plain text Malformed
Fresh token, 15 days later Stale
Fresh token, clock behind a token already seen ClockSetBack

The live demo token is real and decodes, but Clavem signed it with its own key. A verifier built with any other public key has to refuse it. A public key that is not 32 bytes makes Verifier::new return None, so a wrong configuration shows up at startup and not as a customer’s locked screen.

Does this token belong to this key?

kh is the first 16 hex characters of the SHA-256 of the normalized key. Normalization follows the key’s format: Clavem-format keys are uppercased with I and L read as 1, O as 0 and U as V, and any other key is lowercased.

use sha2::{Digest, Sha256};

pub fn matches_key(claims: &Claims, license_key: &str) -> bool {
    let t = license_key.trim();
    let groups: Vec<&str> = t.split('-').collect();
    let native = groups.len() == 5 && groups.iter().all(|g| g.len() == 5 && g.chars().all(|c| c.is_ascii_alphanumeric()));
    let normalized = if native {
        t.to_uppercase().replace(['I', 'L'], "1").replace('O', "0").replace('U', "V")
    } else {
        t.to_lowercase()
    };
    let hex: String = Sha256::digest(normalized.as_bytes()).iter().map(|b| format!("{b:02x}")).collect();
    hex[..16] == claims.kh
}

Against the demo token’s kh, this returned true for the demo key typed as is, lowercase with spaces, and with I and O for 1 and 0. It returned false when the last character changed.

Guard against a clock set back

Store the highest iat you have verified, and pass it as highest_iat. Write it atomically, so a crash cannot leave half a number that parses as zero and quietly removes the guard:

use std::{fs, io, path::Path};

pub fn read_highest(path: &Path) -> i64 {
    fs::read_to_string(path).ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0)
}

pub fn bump_highest(path: &Path, iat: i64) -> io::Result<()> {
    if iat <= read_highest(path) { return Ok(()); }
    let tmp = path.with_extension("tmp");
    fs::write(&tmp, iat.to_string())?;
    fs::rename(tmp, path)
}

Call bump_highest only after check returned Ok. A user who deletes the file defeats it, and nothing offline can prevent that. It stops the casual date change.

Where the token lives

A token is signed, not secret, so a file in the platform’s data directory is enough: a changed byte fails the signature. Keep the license key itself in the credential store, as the validation page shows. The payload includes the buyer’s email address in readable form, so keep tokens out of logs.

Traps in Rust

  • include_str! keeps the trailing newline of the key file. Verifier::new trims for that reason.
  • Do not add #[serde(deny_unknown_fields)] to Claims. A token that gains a field would then fail as malformed.
  • SystemTime::now().duration_since(UNIX_EPOCH) returns an error for a clock before 1970. Treat that as Stale, not as zero.
  • verify accepts signatures that verify_strict rejects. Use verify_strict.

Doing this with Clavem

Each product has its own key pair, and every activate and validate reply carries a token signed with it. The public key is on the product page and in GET /v1/admin/products. For the endpoints, see the API reference.

Questions

Should I use verify or verify_strict in ed25519-dalek?

Use verify_strict. It also rejects signatures that RFC 8032 allows but that can be malleable, and signatures from standard signers pass it. Clavem's tokens do.

Why does VerifyingKey::from_bytes need exactly 32 bytes?

An Ed25519 public key is 32 bytes. Decode the base64url key, convert the bytes into a 32-byte array with try_into, and treat any other length as a configuration bug, not as a bad token.

Can I embed the public key with include_str?

Yes, but include_str keeps the trailing newline of the file. Trim the string before decoding it, or the key will not decode.

Sources

  1. ed25519-dalek 2.2 VerifyingKey::verify_strict (checked November 2026)