Where the sodium functions come from
The PHP manual says the sodium extension has been bundled with PHP since 7.2.0. Some builds still leave it out, so check before you rely on it: function_exists('sodium_crypto_sign_verify_detached').
When the extension is missing, composer require paragonie/sodium_compat defines the same global functions in pure PHP. Its 2.x releases need PHP 8.1 or later. On older PHP use the 1.x line (composer require paragonie/sodium_compat:^1), which the project keeps for PHP 5.2 to 8.0. If you ship a ZIP instead of a Composer project, include the vendor folder.
The verifier
The token format and claims are described on the offline verification reference. This class is PHP 7.4 or later and covers the checks in order: shape, key and signature sizes, signature, JSON, then the claims.
<?php
final class ClavemToken
{
/** Decodes unpadded base64url. Returns false for input that is not valid base64url. */
private static function b64url(string $value)
{
$b64 = strtr($value, '-_', '+/');
return base64_decode($b64 . str_repeat('=', (4 - strlen($b64) % 4) % 4), true);
}
/** Returns the claims when the signature is good, otherwise null. */
public static function verify(string $token, string $publicKey): ?array
{
if (!function_exists('sodium_crypto_sign_verify_detached')) {
throw new RuntimeException('Install ext-sodium or paragonie/sodium_compat.');
}
$parts = explode('.', $token);
if (count($parts) !== 3 || $parts[0] !== 'sgt1') {
return null;
}
$key = self::b64url($publicKey);
$signature = self::b64url($parts[2]);
$body = self::b64url($parts[1]);
if ($key === false || $signature === false || $body === false
|| strlen($key) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
|| strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES) {
return null;
}
// The signed text is the first two parts exactly as received, not the decoded payload.
if (!sodium_crypto_sign_verify_detached($signature, $parts[0] . '.' . $parts[1], $key)) {
return null;
}
$claims = json_decode($body, true);
return is_array($claims) ? $claims : null;
}
/** $productId must be an int: environment variables and .ini values arrive as strings. */
public static function isLicensed(?array $claims, int $productId, ?int $now = null): bool
{
$now = $now ?? time();
return $claims !== null
&& ($claims['v'] ?? null) === 1
&& ($claims['pid'] ?? null) === $productId
&& ($claims['valid'] ?? false) === true
&& (!isset($claims['exp']) || $claims['exp'] > $now)
&& ($claims['refresh_by'] ?? 0) > $now;
}
/** True when the clock is earlier than a token issue time you have already seen: a clock set back. */
public static function clockWentBack(array $claims, int $highestIat, ?int $now = null): bool
{
return ($now ?? time()) + 300 < max($highestIat, (int) $claims['iat']);
}
/** Optional: was this token issued for the key the customer typed? */
public static function matchesKey(array $claims, string $licenseKey): bool
{
$key = trim($licenseKey);
$native = preg_match('/^[0-9A-Za-z]{5}(?:-[0-9A-Za-z]{5}){4}$/', $key) === 1;
$normalized = $native ? strtr(strtoupper($key), ['I' => '1', 'L' => '1', 'O' => '0', 'U' => 'V']) : strtolower($key);
return hash_equals((string) ($claims['kh'] ?? ''), substr(hash('sha256', $normalized), 0, 16));
}
}
clockWentBack() implements the clock check from the reference: store the highest iat you have seen next to the token, and treat a clock earlier than it as stale. It allows five minutes of drift.
Results on test tokens
The real demo product’s public key is not published, so these tokens were signed with a throwaway key pair in the same format. Each row was verified with ClavemToken::verify() and isLicensed() for product 75.
| Token | Signature | isLicensed() |
Why |
|---|---|---|---|
| Fresh, valid | good | true | all checks pass |
Payload edited after signing (pid changed) |
fails | false | verify() returns null |
| Signed by another product’s key | fails | false | verify() returns null |
refresh_by in the past |
good | false | go online once |
valid: false (expired license) |
good | false | the license ended |
pid of another product |
good | false | not this product |
All eight vectors, plus the string-product-id case below, passed on PHP 7.4 with sodium_compat 1.24 and PHP 8.3 with sodium_compat 2.5. Both ran as WebAssembly builds of PHP without the sodium extension, so the polyfill did the signature work. A native ext-sodium run on a normal server is not covered.
PHP traps
- Strings are not integers.
json_decode()returnspidas an int.getenv('PRODUCT_ID')returns"75", and75 === "75"is false, so every customer looks unlicensed. Theint $productIdparameter coerces a numeric string unless you declarestrict_types=1, in which case it throws aTypeError. Either beats a silent false. - Strict base64. The second argument
truetobase64_decode()makes it reject invalid characters. Without it, PHP silently skips characters that are not base64, so a damaged value decodes to different bytes instead of failing at once. - Verify the string, not the payload. Decoding the payload and re-encoding it with
json_encode()produces different bytes, and the signature will never match. - Polyfill speed. Pure PHP is slower than the extension. If profiling shows it, keep the decoded claims in APCu or your cache keyed by a hash of the token.
- Constant, not config. Put the public key in the code. A key read from a settings table is one more value a buyer can paste over.
What the buyer can still do
The buyer owns the server. They can edit isLicensed() or replace the public key with their own and sign tokens themselves. Signature checks stop forged or damaged tokens, a token from your other product, and a stale one. They do not stop someone who edits your PHP.
Servers with no outbound access
A token is a string. A buyer whose server cannot reach the internet can run the validate call from any machine that can, copy the token into your admin screen, and your code verifies it as above. Compare matchesKey() and, if you want it tied to one install, iid or fp. The token lasts until refresh_by, 14 days after it was issued, so they repeat it every two weeks. Clavem has no offline activation flow of its own; this only uses the documented token.
Doing this with Clavem
Each product has its own key pair. Copy the public key from the product page in the dashboard, or from GET /v1/admin/products, into your code. The live call that returns the token is in the validation guide.
Questions
Does PHP need ext-sodium to verify Ed25519 signatures?
Not if you install paragonie/sodium_compat, which defines the same sodium_ functions in pure PHP. It is slower than the extension, so verify once and keep the result instead of verifying in a loop.
Why does a valid token fail verification?
The usual cause is verifying the decoded payload instead of the text sgt1.<payload> exactly as received. The second is a product id read from an environment variable as the string "75" and compared with the integer 75.