The token format and the checks are in the offline verification reference, which has a compact Python version. This page is the version to ship. It reports why a token was refused, takes the clock as an argument so tests need no timers, and covers the places where Python quietly accepts bad input. The call that fetches the token is in license key validation in Python.
pip install pynacl
The verifier
import base64
import hashlib
import json
import re
import time
from typing import Callable
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
_ALPHABET = re.compile(r"^[A-Za-z0-9_-]+$")
def b64url_decode(value: str) -> bytes:
if not _ALPHABET.match(value): # urlsafe_b64decode silently drops characters it does not know
raise ValueError("not base64url")
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
class TokenVerifier:
def __init__(self, public_key: str, product_id: int, now: Callable[[], float] = time.time) -> None:
self._key = VerifyKey(b64url_decode(public_key.strip())) # raises ValueError unless it is 32 bytes
self._product_id = product_id
self._now = now
def claims(self, token: str) -> dict | str:
"""The claims when the signature is good, otherwise 'malformed' or 'bad-signature'."""
parts = token.split(".") if isinstance(token, str) else []
if len(parts) != 3 or parts[0] != "sgt1":
return "malformed"
try:
signature = b64url_decode(parts[2])
payload = b64url_decode(parts[1])
if len(signature) != 64:
return "malformed"
self._key.verify(f"{parts[0]}.{parts[1]}".encode(), signature)
claims = json.loads(payload)
except BadSignatureError:
return "bad-signature"
except ValueError:
return "malformed"
return claims if isinstance(claims, dict) else "malformed"
def check(self, token: str, highest_iat: int = 0) -> str:
"""'ok' or the reason. highest_iat is the largest iat verified before."""
claims = self.claims(token)
if isinstance(claims, str):
return claims
now = self._now()
if claims.get("v") != 1:
return "malformed"
if claims.get("pid") != self._product_id:
return "wrong-product"
if claims.get("valid") is not True: # not just truthy: "false" is a truthy string
return "not-valid"
if "exp" in claims and claims["exp"] <= now:
return "expired"
if now < highest_iat:
return "clock-set-back"
if claims.get("refresh_by", 0) <= now:
return "stale"
return "ok"
Only "ok" should turn the paid features on. "stale" means validate online once. The other values 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 on Python 3.14 with PyNaCl:
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
tampered has a payload edited to extend exp, with the original 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. A public key that is not 32 bytes raises nacl.exceptions.ValueError, a subclass of ValueError, when the verifier is built. Create it at startup, so a wrong key fails at once.
Using cryptography instead
If cryptography is already in your tree, replace VerifyKey with Ed25519PublicKey and the exception with InvalidSignature. The same good token verified and the tampered one raised InvalidSignature:
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
key = Ed25519PublicKey.from_public_bytes(b64url_decode(public_key))
try:
key.verify(b64url_decode(signature_part), f"sgt1.{payload_part}".encode())
except InvalidSignature:
... # not signed by this product's key, or changed after signing
Does this token belong to this key?
kh is 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:
def matches_key(claims: dict, license_key: str) -> bool:
key = license_key.strip()
if re.fullmatch(r"[0-9A-Za-z]{5}(-[0-9A-Za-z]{5}){4}", key):
key = key.upper().replace("I", "1").replace("L", "1").replace("O", "0").replace("U", "V")
else:
key = key.lower()
return hashlib.sha256(key.encode()).hexdigest()[:16] == claims.get("kh")
Against the demo token it returned true for the key as is, in lowercase with spaces, and with I and O for 1 and 0, and false when the last character changed.
The clock guard, and where the token lives
Keep the highest iat you have verified next to the license, and pass it as highest_iat. Update it only after check returned "ok":
saved = storage.load() # {"key", "instance_id", "token", "highest_iat"?}
result = verifier.check(saved["token"], saved.get("highest_iat", 0))
if result == "ok":
iat = verifier.claims(saved["token"])["iat"]
if iat > saved.get("highest_iat", 0):
storage.save({**saved, "highest_iat": iat})
A user who clears the stored license starts over, and nothing offline prevents that. The guard stops the casual date change. A token is signed, not secret, so it needs integrity more than hiding: the keyring entry from the validation page is fine, and so is a file in the user’s data directory. The payload holds the buyer’s email in readable form, so keep tokens out of logs.
Traps in Python
urlsafe_b64decodedoes not reject bad characters.base64.urlsafe_b64decode("AB!!CD==")returned 3 bytes without an error. The verifier checks the alphabet first.- Truthy is not true.
bool("false")isTrue. Comparevalidwithis True. json.loadsaccepts what Python accepts, such asNaN. Signed payloads from Clavem never contain it, but check that the result is adict, as the code does.- PyInstaller and Nuitka. PyNaCl ships a compiled libsodium. Run the frozen build 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
PyNaCl or cryptography for Ed25519 in Python?
Both verify Ed25519 correctly. PyNaCl is smaller and wraps libsodium. cryptography is larger but is often already a dependency. Use whichever you already ship, and do not add both.
Why does base64.urlsafe_b64decode need padding?
Clavem's tokens use base64url without padding, and Python's decoder requires the length to be a multiple of 4. Add equals signs until it is, and check the alphabet first, because the decoder silently skips characters it does not know.
Why compare valid with is True?
A truthy check accepts any non-empty string, including the text false. The token is signed, so this cannot be forged, but an exact comparison keeps the check honest if a field ever changes type.