In a desktop application that works offline, a license key has to be verified without asking a server. Asymmetric signatures fit that job: the private key stays in the tool that issues licenses, and only the public key is embedded in the application. This article covers P-256 signatures with .NET's ECDsa class, the signed document format, signature encodings, key management and Crockford Base32 for hand-typed keys.
Why a signature rather than HMAC
HMAC is symmetric: the verifier needs the same key that produces signatures. If that key is embedded in the application, anyone who extracts it can issue valid licenses. With ECDSA, verification uses the public key, and obtaining the public key is not enough to produce a new signature.
This is a deterrent, not absolute protection. Client code can be modified and the verification step skipped. The goal is to make made-up keys and key sharing harder while giving honest users a smooth experience that needs no network connection. Prefer clear error messages over aggressive checks that punish the user.
The signed document format
The license is serialized as JSON; the JSON bytes and the signature are base64url-encoded and joined with a dot: payload.signature. The verifier checks the signature of the received bytes first and parses the JSON only when the signature is valid. Parsing and re-serializing before verifying is a mistake: a whitespace or field-order difference breaks the signature, and unverified data reaches the parser early.
base64url uses - and _ instead of + and / and drops padding, so the key causes no trouble in an email or a file name. The System.Buffers.Text.Base64Url class introduced in .NET 9 performs the conversion directly. Malformed input throws FormatException or JsonException; these map to an invalid key result instead of crashing the application.
using System.Buffers.Text;
using System.Security.Cryptography;
using System.Text.Json;
public sealed record License(string Edition, string LicensedTo, DateOnly IssuedOn, string? InstallationId);
public static class LicenseCodec
{
public static string Sign(License license, ECDsa privateKey)
{
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(license);
byte[] signature = privateKey.SignData(payload, HashAlgorithmName.SHA256); // IEEE P1363, 64 bytes
return Base64Url.EncodeToString(payload) + "." + Base64Url.EncodeToString(signature);
}
public static License? Verify(string token, ECDsa publicKey)
{
string[] parts = token.Trim().Split('.');
if (parts.Length != 2) return null;
try
{
byte[] payload = Base64Url.DecodeFromChars(parts[0]);
byte[] signature = Base64Url.DecodeFromChars(parts[1]);
if (!publicKey.VerifyData(payload, signature, HashAlgorithmName.SHA256)) return null;
return JsonSerializer.Deserialize<License>(payload); // parse only verified bytes
}
catch (Exception e) when (e is FormatException or JsonException) { return null; }
}
}IEEE P1363 and DER signature formats
An ECDSA signature consists of two integers, r and s. .NET's SignData uses the IEEE P1363 format by default: for P-256, r and s are 32 bytes each, so the signature is a fixed 64 bytes. OpenSSL, Java and the X.509 world mostly use the DER-encoded ASN.1 sequence from RFC 3279 instead; its length varies and is at most 72 bytes for P-256.
If the license tool is written in another language, state explicitly that both sides use the same format. On .NET 5 and later, the DSASignatureFormat parameter supports both. In the default implementations, ECDSA signatures use a random value, so signing the same data twice gives different signatures. Tests therefore do not compare a fixed signature; they check the sign-verify round trip and verify a known-good sample generated earlier.
Microsoft Learn — DSASignatureFormat
Key generation, PEM and key rotation
Generate the key pair with ECDsa.Create(ECCurve.NamedCurves.nistP256). ExportPkcs8PrivateKeyPem turns the private key into PKCS#8 PEM text and ExportSubjectPublicKeyInfoPem turns the public key into SubjectPublicKeyInfo PEM. The private key never goes into version control; keep it in an access-restricted file on the machine that runs the license tool, or in a key vault.
ImportFromPem ignores unsupported PEM blocks and throws if it finds more than one supported block, so the text embedded in the application must contain a single PUBLIC KEY block. When moving to a new key, the old public key stays in the application: the verifier tries each key in turn, or an unsigned key id is prefixed to the document. A wrong id only makes verification fail.
using System.Security.Cryptography;
public static class LicenseKeys
{
// License tool only: the private key never ships with the application.
public static void Generate(string directory)
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
File.WriteAllText(Path.Combine(directory, "signing.key.pem"), key.ExportPkcs8PrivateKeyPem());
File.WriteAllText(Path.Combine(directory, "signing.pub.pem"), key.ExportSubjectPublicKeyInfoPem());
}
// Application: every public key that may still have signed a license.
private static readonly string[] PublicKeyPems =
[
"""
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----
""",
];
public static License? Verify(string token)
{
foreach (string pem in PublicKeyPems)
{
using var key = ECDsa.Create();
key.ImportFromPem(pem); // throws if several supported blocks exist
if (LicenseCodec.Verify(token, key) is { } license) return license;
}
return null;
}
}
// Interop with a tool that emits DER signatures:
// key.VerifyData(payload, der, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);Microsoft Learn — ECAlgorithm.ImportFromPem
Installation binding and error kinds
To bind a license to one installation, the application creates a random installation id on first launch and writes it to the user data folder. The user passes that id to the license tool, the tool adds it to the signed document, and the verifier compares the value in the document with the local one. Using a random id instead of a hardware fingerprint collects no personal data and does not break the license when hardware changes.
Write the id file atomically: a temp file first, then a rename. Return the verification result as a detailed type rather than a single bool: malformed, invalid signature, belongs to another installation, unsupported version. Messages that tell users what to do in each case reduce support load.
Hand-typed keys: Crockford Base32
A long base64url string is fine for copy and paste; for a short code read off a phone and typed in, Crockford Base32 is more practical. The alphabet consists of digits and the uppercase letters except I, L, O and U. When decoding, lowercase is uppercased, O becomes zero, I and L become one, and hyphens added for readability are ignored.
A check character at the end catches typing mistakes early. With odd weights, every single-character error is caught modulo 32; but 32 is not prime, so swapping two adjacent characters whose values differ by 16 can slip through. Crockford's suggested mod-37 check closes that gap thanks to the prime modulus, at the cost of five extra symbols. The check character provides no security; the signature does the real verification.
using System.Text;
public static class Crockford
{
private const string Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
public static string Normalize(string input)
{
var sb = new StringBuilder(input.Length);
foreach (char raw in input.ToUpperInvariant())
{
char c = raw switch { 'O' => '0', 'I' or 'L' => '1', _ => raw };
if (c == '-' || char.IsWhiteSpace(c)) continue;
if (Alphabet.IndexOf(c) < 0) throw new FormatException($"Invalid character '{raw}'");
sb.Append(c);
}
return sb.ToString();
}
// Odd weights catch every single-character substitution modulo 32.
public static char CheckChar(string normalized)
{
int sum = 0;
for (int i = 0; i < normalized.Length; i++)
sum = (sum + Alphabet.IndexOf(normalized[i]) * (2 * i + 1)) % 32;
return Alphabet[sum];
}
}
// Crockford.Normalize("ab-cd-lo") == "ABCD10"; shown to users as groups of five.