The token format and the claim checks are in the offline verification reference, which has examples in other languages. This page is the C++ version: OpenSSL’s EVP interface, a small base64url decoder, and a verifier class that reports why a token was refused. It takes now as an argument so tests need no timers. The call that fetches the token is in license key validation in C++.
The verifier
OpenSSL has supported Ed25519 since 1.1.1. A raw 32-byte public key goes into EVP_PKEY_new_raw_public_key, and verification is one call:
#include <openssl/evp.h>
#include <nlohmann/json.hpp>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>
using json = nlohmann::json;
enum class Check { Ok, Malformed, BadSignature, WrongProduct, NotValid, Expired, Stale, ClockSetBack };
/// Decodes unpadded base64url. Returns nullopt for any character outside the alphabet.
std::optional<std::vector<unsigned char>> b64url_decode(const std::string& in) {
static const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
if (in.empty() || in.size() % 4 == 1) return std::nullopt;
std::vector<unsigned char> out;
uint32_t acc = 0;
int bits = 0;
for (char c : in) {
auto pos = alphabet.find(c);
if (pos == std::string::npos) return std::nullopt;
acc = (acc << 6) | static_cast<uint32_t>(pos);
bits += 6;
if (bits >= 8) { bits -= 8; out.push_back(static_cast<unsigned char>((acc >> bits) & 0xFF)); }
}
return out;
}
struct PkeyDeleter { void operator()(EVP_PKEY* k) const { EVP_PKEY_free(k); } };
struct CtxDeleter { void operator()(EVP_MD_CTX* c) const { EVP_MD_CTX_free(c); } };
class TokenVerifier {
public:
/// public_key: 32 raw bytes, base64url. Throws std::invalid_argument when it is not a key.
TokenVerifier(const std::string& public_key, int64_t product_id) : product_id_(product_id) {
auto raw = b64url_decode(public_key);
if (!raw || raw->size() != 32) throw std::invalid_argument("public key must be 32 bytes, base64url");
key_.reset(EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, raw->data(), raw->size()));
if (!key_) throw std::invalid_argument("not an Ed25519 public key");
}
/// Fills `claims` when the signature is good. Returns Ok, Malformed or BadSignature.
Check claims(const std::string& token, json& claims) const {
auto first = token.find('.');
auto second = first == std::string::npos ? first : token.find('.', first + 1);
if (first == std::string::npos || second == std::string::npos || token.find('.', second + 1) != std::string::npos) return Check::Malformed;
if (token.substr(0, first) != "sgt1") return Check::Malformed;
auto signature = b64url_decode(token.substr(second + 1));
auto payload = b64url_decode(token.substr(first + 1, second - first - 1));
if (!signature || signature->size() != 64 || !payload) return Check::Malformed;
const std::string signed_text = token.substr(0, second); // "sgt1.<payload>", exactly as received
std::unique_ptr<EVP_MD_CTX, CtxDeleter> ctx(EVP_MD_CTX_new());
if (!ctx || EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, key_.get()) != 1) return Check::Malformed;
// Ed25519 is one-shot: use EVP_DigestVerify, not EVP_DigestVerifyUpdate and Final.
int ok = EVP_DigestVerify(ctx.get(), signature->data(), signature->size(),
reinterpret_cast<const unsigned char*>(signed_text.data()), signed_text.size());
if (ok != 1) return Check::BadSignature;
claims = json::parse(payload->begin(), payload->end(), nullptr, false);
return claims.is_object() ? Check::Ok : Check::Malformed;
}
Check check(const std::string& token, int64_t now, int64_t highest_iat = 0) const {
json c;
if (Check r = claims(token, c); r != Check::Ok) return r;
if (c.value("v", 0) != 1) return Check::Malformed;
if (c.value("pid", int64_t{-1}) != product_id_) return Check::WrongProduct;
if (c.value("valid", false) != true) return Check::NotValid;
if (c.contains("exp") && c["exp"].get<int64_t>() <= now) return Check::Expired;
if (now < highest_iat) return Check::ClockSetBack;
if (c.value("refresh_by", int64_t{0}) <= now) return Check::Stale;
return Check::Ok;
}
private:
std::unique_ptr<EVP_PKEY, PkeyDeleter> key_;
int64_t product_id_;
};
Only Check::Ok should turn paid features on, and Stale means validate online once. Build the verifier once at startup. The constructor throws for a bad key, which you want to see during development and not as a customer’s locked screen.
Test results
The tokens were signed with a throwaway key in the documented sgt1 format, and the verifier held its public half. Built with clang++ against OpenSSL 3, the program printed:
good ok
withExp ok
expiredExp expired
stale stale
notValid not-valid
wrongProduct wrong-product
wrongVersion malformed
signedByOtherKey bad-signature
tampered bad-signature
twoParts malformed
fourParts malformed
wrongPrefix malformed
garbage malformed
realDemoSignedByClavem bad-signature
highest iat in the future -> clock-set-back
15 days later -> stale
short key throws: public key must be 32 bytes, base64url
b64url 'AB!!CD' -> rejected
tampered is a good token whose payload was edited to extend exp, with the old signature. realDemoSignedByClavem is the live demo token. It decodes, but Clavem signed it with its own key, so a verifier built with any other public key must refuse it.
OpenSSL traps
- Pass a null digest.
EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, key)has no digest argument for Ed25519. Naming one makes the call fail. - Mind the return value.
EVP_DigestVerifyreturns 1 for a good signature, 0 for a bad one and a negative number for an error. Compare with 1, never with “non-zero”. - The error queue fills up. OpenSSL can leave entries in its thread-local error queue after a failed call. If other code in your process reads that queue, call
ERR_clear_error()after a failure. - Link the right library. On macOS the system
libcryptois not OpenSSL 3, and the SDK has no OpenSSL headers. Install and link OpenSSL, or use libsodium instead. get<int64_t>()throws on a non-number. The token is signed, so this cannot be forged, but wrapcheckin atryso a surprise cannot take the app down.
Key, clock and storage
kh ties a token to the key the customer typed. It is the first 16 hex characters of the SHA-256 of the normalized key: uppercased with I and L read as 1, O as 0 and U as V for a Clavem-format key, and lowercased otherwise. Hash with EVP_Digest and EVP_sha256().
For the clock, keep the highest iat you have verified in the same Keychain or DPAPI blob as the license key (see the validation page). Pass it as highest_iat, and raise it only after check returned Ok. A user who deletes the blob starts over, and nothing offline can stop that. The guard stops the casual date change.
A token is signed, not secret, so it needs integrity more than hiding. A file in the user’s data directory is enough, because a changed byte fails the signature. The payload includes the buyer’s email in readable form, so keep tokens out of logs and crash dumps.
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
Why does EVP_DigestVerifyUpdate not work for Ed25519?
Ed25519 signs and verifies the whole message at once. OpenSSL exposes that through the one-shot EVP_DigestVerify, with a null digest passed to EVP_DigestVerifyInit. The streaming Update and Final calls do not apply.
Can I use libsodium instead of OpenSSL?
Yes. crypto_sign_verify_detached takes the signature, the message and the 32-byte public key, and returns 0 on success. Use it if you already link libsodium. The checks on the claims are the same.
What type should I use for the timestamps?
int64_t. Tokens carry seconds since the Unix epoch, and a 32-bit time_t overflows in 2038 on platforms that still have one.