The offline verification reference describes the token and the checks, and offline verification in C++ does the same with OpenSSL. This page is the Qt version: libsodium for the signature, and Qt’s own types for decoding and JSON. The call that fetches the token is in license key validation in Qt.
None of the Qt code here was compiled, because no Qt installation was available. The algorithm was run in other languages against the same test tokens, and the results are in the table below.
The verifier
libsodium needs sodium_init() once. crypto_sign_verify_detached takes the signature, the message and the 32-byte public key, and returns 0 for a good signature. Link it with find_package or pkg_check_modules in CMake.
#include <QByteArray>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <optional>
#include <stdexcept>
#include <sodium.h>
class TokenVerifier {
public:
enum class Check { Ok, Malformed, BadSignature, WrongProduct, NotValid, Expired, Stale, ClockSetBack };
/// publicKey: 32 raw bytes, base64url, from the product page. Throws when it is not a key.
TokenVerifier(const QString& publicKey, qint64 productId) : m_product(productId) {
if (sodium_init() < 0) throw std::runtime_error("libsodium failed to initialise");
auto raw = decode(publicKey.trimmed().toLatin1());
if (!raw || raw->size() != int(crypto_sign_PUBLICKEYBYTES)) throw std::invalid_argument("public key must be 32 bytes, base64url");
m_key = *raw;
}
Check claims(const QString& token, QJsonObject* out) const {
const QList<QByteArray> parts = token.toLatin1().split('.');
if (parts.size() != 3 || parts[0] != "sgt1") return Check::Malformed;
const auto signature = decode(parts[2]);
const auto payload = decode(parts[1]);
if (!signature || signature->size() != int(crypto_sign_BYTES) || !payload) return Check::Malformed;
const QByteArray signedText = parts[0] + '.' + parts[1]; // the text exactly as received
const int rc = crypto_sign_verify_detached(
reinterpret_cast<const unsigned char*>(signature->constData()),
reinterpret_cast<const unsigned char*>(signedText.constData()), static_cast<unsigned long long>(signedText.size()),
reinterpret_cast<const unsigned char*>(m_key.constData()));
if (rc != 0) return Check::BadSignature;
QJsonParseError error;
const QJsonDocument doc = QJsonDocument::fromJson(*payload, &error);
if (error.error != QJsonParseError::NoError || !doc.isObject()) return Check::Malformed;
*out = doc.object();
return Check::Ok;
}
Check check(const QString& token, qint64 now = QDateTime::currentSecsSinceEpoch(), qint64 highestIat = 0) const {
QJsonObject c;
if (Check r = claims(token, &c); r != Check::Ok) return r;
if (c["v"].toInteger(0) != 1) return Check::Malformed;
if (c["pid"].toInteger(-1) != m_product) return Check::WrongProduct;
if (!(c["valid"].isBool() && c["valid"].toBool())) return Check::NotValid;
if (c.contains("exp") && c["exp"].toInteger() <= now) return Check::Expired;
if (now < highestIat) return Check::ClockSetBack;
if (c["refresh_by"].toInteger(0) <= now) return Check::Stale;
return Check::Ok;
}
private:
/// Unpadded base64url. Returns nullopt on a bad character.
static std::optional<QByteArray> decode(const QByteArray& in) {
const QByteArray padded = in + QByteArray((4 - in.size() % 4) % 4, '=');
const auto result = QByteArray::fromBase64Encoding(padded, QByteArray::Base64UrlEncoding | QByteArray::AbortOnBase64DecodingErrors);
if (!result) return std::nullopt;
return *result;
}
QByteArray m_key;
qint64 m_product;
};
Build one verifier at startup. The constructor throws for a bad key, so a build mistake shows up on your machine and not on a customer’s.
What the checks give
These are the results of the same logic, run on a set of test tokens signed with a throwaway key in the documented sgt1 format. They were confirmed in the Swift, Rust, Python and C++ versions of this guide. The Qt 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 |
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 Qt:
const QByteArray hex = QCryptographicHash::hash(normalized.toUtf8(), QCryptographicHash::Sha256).toHex();
const bool sameKey = hex.left(16) == claims["kh"].toString().toLatin1();
For the clock, keep the highest iat you have verified next to the license in QtKeychain, as in the validation guide, and pass it as highestIat. Raise it only after a check returned Ok. A user who deletes the entry starts over, and nothing offline can stop that. It stops the casual date change.
A token is signed, not secret, so it needs integrity more than hiding. Store it in a file under QStandardPaths::writableLocation(QStandardPaths::AppDataLocation). Its payload includes the buyer’s email address in readable form, so keep it out of qDebug output and crash reports.
Qt traps
QByteArray::fromBase64cannot report errors. By default it skips what it does not understand. UsefromBase64EncodingwithAbortOnBase64DecodingErrorsand test the result.- Read timestamps with
toInteger(). It is 64-bit.toInt()is 32-bit and overflows for times after 2038. QString::toLatin1for the token. Tokens are ASCII. A non-ASCII character becomes a?, and the check then fails as malformed, which is the right outcome.- Call
sodium_init()once, from the main thread, before other threads verify.
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 Qt have Ed25519 signature verification built in?
No. QtCore has hashes and message authentication codes, and QtNetwork has TLS, but no Ed25519 verification call. Add libsodium, or OpenSSL as shown in the C++ guide, and call it from your Qt code.
Why add the padding myself before fromBase64Encoding?
Clavem encodes tokens as unpadded base64url. Adding equals signs until the length is a multiple of 4 gives the decoder the form every implementation accepts, and AbortOnBase64DecodingErrors then reports bad characters instead of skipping them.
Why use fromBase64Encoding and not fromBase64?
By default fromBase64 skips characters it does not know and cannot report a failure. fromBase64Encoding returns a result you can test, and with AbortOnBase64DecodingErrors a malformed token is reported as malformed.