Clavem

Verify a Clavem license token offline in C#

The .NET base class library has no Ed25519 type, so add NSec or BouncyCastle. Split the token on dots, decode unpadded base64url, verify the signature over "sgt1.<payload>" with NSec's Ed25519.Verify, then read the claims with JsonDocument and check v, pid, valid, exp and refresh_by.

The token format and the claim checks are in the offline verification reference, which covers other languages. This page is the C# version. It reports why a token was refused, takes the clock as a parameter so tests need no timers, and handles the places where .NET’s base64 and JSON types are more lenient than you want. The call that fetches the token is in license key validation in C#. The C# code in this guide was not compiled or run, because no .NET SDK was available. The algorithm was run in other languages against the same test tokens.

dotnet add package NSec.Cryptography

The verifier

using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using NSec.Cryptography;

public enum CheckResult { Ok, Malformed, BadSignature, WrongProduct, NotValid, Expired, Stale, ClockSetBack }

public sealed partial class TokenVerifier
{
    private readonly PublicKey _key;
    private readonly long _productId;
    private readonly Func<DateTimeOffset> _now;

    /// <param name="publicKey">32 raw bytes, base64url, from your product page.</param>
    public TokenVerifier(string publicKey, long productId, Func<DateTimeOffset>? now = null)
    {
        var raw = Decode(publicKey.Trim());
        if (raw is not { Length: 32 } || !PublicKey.TryImport(SignatureAlgorithm.Ed25519, raw, KeyBlobFormat.RawPublicKey, out var key))
            throw new ArgumentException("The public key must be 32 bytes, base64url.", nameof(publicKey));
        _key = key!;
        _productId = productId;
        _now = now ?? (() => DateTimeOffset.UtcNow);
    }

    [GeneratedRegex("^[A-Za-z0-9_-]+$")]
    private static partial Regex Alphabet();

    /// Unpadded base64url. Convert.FromBase64String ignores whitespace, so the alphabet is checked first.
    private static byte[]? Decode(string s)
    {
        if (s.Length == 0 || s.Length % 4 == 1 || !Alphabet().IsMatch(s)) return null;
        var std = s.Replace('-', '+').Replace('_', '/');
        std = std.PadRight(std.Length + (4 - std.Length % 4) % 4, '=');
        try { return Convert.FromBase64String(std); } catch (FormatException) { return null; }
    }

    /// Returns Ok and the parsed payload when the signature is good.
    public CheckResult Claims(string token, out JsonDocument? claims)
    {
        claims = null;
        var parts = token.Split('.');
        if (parts.Length != 3 || parts[0] != "sgt1") return CheckResult.Malformed;
        var signature = Decode(parts[2]);
        var payload = Decode(parts[1]);
        if (signature is not { Length: 64 } || payload is null) return CheckResult.Malformed;

        var signed = Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]);   // the text exactly as received
        if (!SignatureAlgorithm.Ed25519.Verify(_key, signed, signature)) return CheckResult.BadSignature;
        try { claims = JsonDocument.Parse(payload); }
        catch (JsonException) { return CheckResult.Malformed; }
        return claims.RootElement.ValueKind == JsonValueKind.Object ? CheckResult.Ok : CheckResult.Malformed;
    }

    /// highestIat is the largest iat verified before.
    public CheckResult Check(string token, long highestIat = 0)
    {
        var result = Claims(token, out var doc);
        if (result != CheckResult.Ok) return result;
        using (doc)
        {
            var c = doc!.RootElement;
            long Num(string name, long fallback) =>
                c.TryGetProperty(name, out var p) && p.ValueKind == JsonValueKind.Number && p.TryGetInt64(out var n) ? n : fallback;

            var now = _now().ToUnixTimeSeconds();
            if (Num("v", 0) != 1) return CheckResult.Malformed;
            if (Num("pid", -1) != _productId) return CheckResult.WrongProduct;
            if (!(c.TryGetProperty("valid", out var v) && v.ValueKind == JsonValueKind.True)) return CheckResult.NotValid;
            if (c.TryGetProperty("exp", out _) && Num("exp", 0) <= now) return CheckResult.Expired;
            if (now < highestIat) return CheckResult.ClockSetBack;
            if (Num("refresh_by", 0) <= now) return CheckResult.Stale;
            return CheckResult.Ok;
        }
    }
}

Only CheckResult.Ok should turn the paid features on, and Stale means validate online once. Create one verifier at startup. The constructor throws for a bad key, so a build mistake shows up in development.

If you prefer no native dependency, BouncyCastle’s Org.BouncyCastle.Math.EC.Rfc8032.Ed25519.Verify takes the signature, the public key and the message as byte arrays and returns a bool, so it replaces only the one Verify line. NSec’s native libsodium is bundled for common runtimes, so check that your publish target, such as a trimmed or AOT build, still includes it.

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 C# 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) 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, with a different public key 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. Test with an xUnit theory and a fixed now function, 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. In .NET, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(normalized)))[..16] gives the value to compare, and ToHexStringLower needs .NET 9. On earlier versions call ToLowerInvariant() on Convert.ToHexString.

For the clock, add a HighestIat field to the Saved record from the validation page, so it lives in the same DPAPI-protected blob. Pass it as highestIat, and raise it only after Check returned Ok. A user who deletes the file starts over, and nothing offline can prevent that. The guard stops the casual date change.

A token is signed, not secret, so it needs integrity more than hiding. The payload includes the buyer’s email in readable form, so keep tokens out of logs and telemetry.

Traps in .NET

  • Convert.FromBase64String ignores whitespace and rejects missing padding. Check the alphabet and pad, as above.
  • JsonDocument is IDisposable. It rents memory, so wrap it in using, as the code does.
  • Do not read timestamps with GetInt32. Use TryGetInt64. A 32-bit value overflows for times after 2038.
  • DateTime.Now is local time. Use DateTimeOffset.UtcNow.ToUnixTimeSeconds().

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 .NET have Ed25519 built in?

Not in the System.Security.Cryptography namespace as documented for .NET 9 and .NET 10, which lists other algorithms but no Ed25519 type. Use the NSec.Cryptography package, which wraps libsodium, or BouncyCastle, which is pure managed code.

NSec or BouncyCastle?

NSec is small and fast, and it ships a native libsodium for the common platforms. BouncyCastle has no native dependency, which helps with unusual targets or trimming. Both verify the same signatures.

Why does Convert.FromBase64String need care?

It ignores whitespace and needs padding, while Clavem's tokens use unpadded base64url. Check the alphabet first, swap the two URL-safe characters, add the padding, then decode.

Sources

  1. Microsoft Learn, System.Security.Cryptography namespace, .NET 10 (checked November 2026)
  2. NSec on GitHub (checked November 2026)