The token format, the claims and the seven verification steps are in the offline verification reference, which also has a short Swift version. This page adds what a shipping app needs on top: a reason for every refusal, a test table with real results, key and device binding, and a guard against a clock set back. The online call that produces the token is in license key validation in Swift.
Verify and check
claims(in:) returns claims only when the signature is good. check(_:) then applies the documented rules and says which one failed. The clock is injectable, so tests do not wait 14 days.
import CryptoKit
import Foundation
struct LicenseClaims: Decodable {
let v: Int, lid: Int, pid: Int
let kh: String, status: String
let valid: Bool
let iid: String?, fp: String?, email: String?
let iat: Int
let exp: Int?
let refresh_by: Int
}
enum TokenCheck: Equatable {
case ok, malformed, badSignature, wrongProduct, notValid, expired, stale, clockSetBack
}
struct TokenVerifier {
let publicKey: String // 32 raw bytes, base64url, from your product page
let productID: Int
var now: () -> Date = Date.init
func claims(in token: String) -> LicenseClaims? {
let parts = token.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 3, parts[0] == "sgt1",
let keyBytes = Data(base64URL: publicKey), keyBytes.count == 32,
let key = try? Curve25519.Signing.PublicKey(rawRepresentation: keyBytes),
let signature = Data(base64URL: String(parts[2])),
let body = Data(base64URL: String(parts[1])) else { return nil }
let signed = Data("\(parts[0]).\(parts[1])".utf8) // the text exactly as received
guard key.isValidSignature(signature, for: signed) else { return nil }
return try? JSONDecoder().decode(LicenseClaims.self, from: body)
}
func check(_ token: String, highestIssuedAt: Int = 0) -> TokenCheck {
let parts = token.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 3, parts[0] == "sgt1" else { return .malformed }
guard let c = claims(in: token) else {
return Data(base64URL: String(parts[1])) == nil ? .malformed : .badSignature
}
let t = Int(now().timeIntervalSince1970)
if c.v != 1 { return .malformed }
if c.pid != productID { return .wrongProduct }
if !c.valid { return .notValid }
if let exp = c.exp, exp <= t { return .expired }
if t < highestIssuedAt { return .clockSetBack }
if c.refresh_by <= t { return .stale }
return .ok
}
}
extension Data {
init?(base64URL string: String) {
var s = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
s += String(repeating: "=", count: (4 - s.count % 4) % 4)
self.init(base64Encoded: s)
}
}
Test it with real results
The tokens below were signed with a throwaway Ed25519 key in the documented sgt1 format, and the verifier was given that key’s public half. Output from Swift 6.3 on macOS, in a command-line target:
| Token | Result |
|---|---|
| Fresh, perpetual | 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 |
pid of another product |
wrongProduct |
v is 2 |
malformed |
Payload edited to exp far in the future, old signature |
badSignature |
| Signed by a different key | badSignature |
| The live demo token, with this test key | badSignature |
Two parts, four parts, sgt2 prefix, plain text |
malformed |
| Fresh token, 15 days later | stale |
| Fresh token, clock earlier than a token already seen | clockSetBack |
The live demo token is real and decodes, but Clavem signed it with its own key, so a verifier holding any other public key must refuse it. That is the point of the pid and signature checks together: a token from your other product, or from anyone else, never turns this one on.
Bind the token to the key and to this Mac
A valid token is not tied to a device. Two extra comparisons close that gap when you want them. kh is the first 16 hex characters of the SHA-256 of the normalized key, and iid is the activation instance id:
func matches(_ claims: LicenseClaims, licenseKey: String) -> Bool {
let trimmed = licenseKey.trimmingCharacters(in: .whitespacesAndNewlines)
let native = trimmed.range(of: "^[0-9A-Za-z]{5}(-[0-9A-Za-z]{5}){4}$", options: .regularExpression) != nil
let normalized = native
? trimmed.uppercased().replacingOccurrences(of: "[IL]", with: "1", options: .regularExpression)
.replacingOccurrences(of: "O", with: "0").replacingOccurrences(of: "U", with: "V")
: trimmed.lowercased()
let hex = SHA256.hash(data: Data(normalized.utf8)).map { String(format: "%02x", $0) }.joined()
return String(hex.prefix(16)) == claims.kh
}
// claims.iid == the instance id you stored at activation
Against the demo token’s kh, the demo key matches when typed in lowercase with spaces, and when typed with I and O for 1 and 0. A key that differs in the last character does not.
Guard against a clock set back
A customer can set the clock back to keep an old token fresh. Store the highest iat you have verified, and refuse when the clock is earlier. Keep it in the Keychain (see the KeychainStore on the validation page), not in UserDefaults, which is a plain file anyone can edit:
let highest = Int(store.get("highest-iat") ?? "") ?? 0
let result = verifier.check(token, highestIssuedAt: highest)
if result == .ok, let c = verifier.claims(in: token), c.iat > highest {
store.set(String(c.iat), for: "highest-iat")
}
Update it only from a token that passed. This does not stop a determined user who deletes the Keychain item, and nothing offline can. It stops the casual date change.
Where the token lives
A token is signed, not secret, so it needs integrity more than hiding. The Keychain is still the easiest place, next to the key. An Application Support file works too: a changed byte fails the signature. The payload includes the buyer’s email address in readable form, so keep tokens out of logs and crash reports.
Traps in Swift
Data(base64Encoded:)rejects unpadded and URL-safe input. Use thebase64URLinitializer above for the key, the payload and the signature.Curve25519.Signing.PublicKey(rawRepresentation:)throws for anything but 32 bytes. A key pasted with a trailing newline fails here, so trim it.- Decode
validafter the signature, not before. Clavem issues signed tokens for expired and disabled licenses, withvalidset tofalse. expis absent for perpetual licenses, so it must be optional in theDecodablestruct.
Doing this with Clavem
Every activate and validate response carries a token, and each product has its own key pair. The public half is on the product page in the dashboard, and GET /v1/admin/products returns it as public_key. Shipping it in the app is the intended use. See the API reference for the endpoints.
Questions
Does Swift have Ed25519 built in?
Yes. CryptoKit has Curve25519.Signing, which verifies Ed25519 signatures on macOS 10.15, iOS 13 and later. You pass the 32 raw bytes of the public key and the 64 signature bytes.
Why does Data(base64Encoded:) fail on a token part?
Clavem uses unpadded base64url, and Data(base64Encoded:) only reads padded standard base64. Swap - for +, _ for /, and add = until the length is a multiple of 4.
How long does a token stay valid offline?
Until its refresh_by claim, which is 14 days after it was issued, or until exp if the license expires sooner. After that the app has to validate online once.