DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How to keep signed license keys short

A fully-formed license key is a signed document. It carries a licensee, a tier, an expiry, a machine binding and a list of entitlements, and it is signed so a client can trust it offline. The trouble is that all of that adds up. An Ed25519 signature is a fixed 64 bytes. A compact entitlement payload is easily 200–400 bytes more. Base64 the concatenation and you hand the customer a 500-character string to paste into a dialog box. People mistype it, email clients wrap it, and support tickets pile up.

The instinct is to compress the payload. The instinct is right — but the obvious way to do it is a trap that silently breaks verification on a subset of machines.

The ordering that fails

The tempting pipeline is compress, then sign the compressed bytes. On the client you then recompress the payload and check the signature against the result. This appears to work on your machine and fails in the field, because DEFLATE output is not canonical. The RFC 1951 bitstream a compressor emits depends on the implementation, the compression level, the window, and the version of the runtime. Two correct DEFLATE encoders can produce different bytes for the same input, and both decompress back to the same payload. The moment a client runs a different System.IO.Compression than the one that signed the key — a newer .NET, a different OS — its recompressed bytes diverge, the signature mismatches, and a legitimately licensed customer is locked out.

Signatures must be computed over bytes you can reproduce exactly. Compressed bytes are not those bytes.

The ordering that works

Sign the canonical plaintext. Treat compression as an envelope that the client opens before it verifies anything.

The signature is taken over the canonical payload P. DEFLATE is only an envelope; the client decompresses to recover the exact P before verifying.

The key is a small framed buffer: a one-byte magic marker, a one-byte flags field, the body, and the fixed-length signature. Because an Ed25519 signature is always 64 bytes, the decoder splits the buffer by taking the signature off the tail — no length prefix needed.

public static class LicenseKeyCodec
{
    private const byte FormatMagic = 0x4B;          // 'K'
    private const byte FlagDeflate = 0b0000_0001;
    private const int  MaxPayloadBytes = 8 * 1024;  // inflate guard

    public static string Encode(ReadOnlySpan<byte> canonicalPayload,
                                ReadOnlySpan<byte> signature)
    {
        byte[] deflated = Deflate(canonicalPayload);

        // Compression can *expand* a tiny payload. Keep whichever is smaller.
        bool useDeflate = deflated.Length < canonicalPayload.Length;
        ReadOnlySpan<byte> body = useDeflate ? deflated : canonicalPayload;
        byte flags = useDeflate ? FlagDeflate : (byte)0;

        var buf = new byte[2 + body.Length + signature.Length];
        buf[0] = FormatMagic;
        buf[1] = flags;
        body.CopyTo(buf.AsSpan(2));
        signature.CopyTo(buf.AsSpan(2 + body.Length));

        return Group(Base64Url.Encode(buf));
    }

    public static (byte[] payload, byte[] signature) Decode(string key,
                                                            int signatureLength)
    {
        byte[] buf = Base64Url.Decode(Ungroup(key));
        if (buf.Length < 2 + signatureLength || buf[0] != FormatMagic)
            throw new FormatException("Not a Keyright license key.");

        int bodyLen = buf.Length - 2 - signatureLength;
        if (bodyLen < 0) throw new FormatException("Truncated license key.");

        var body = buf.AsSpan(2, bodyLen);
        var signature = buf.AsSpan(2 + bodyLen, signatureLength).ToArray();

        byte[] payload = (buf[1] & FlagDeflate) != 0
            ? Inflate(body, MaxPayloadBytes)
            : body.ToArray();

        return (payload, signature);   // verification happens on `payload`
    }
}
Enter fullscreen mode Exit fullscreen mode

Decode deliberately stops at recovering the plaintext. The caller then runs the normal Ed25519 check against that recovered payload:

var (payload, signature) = LicenseKeyCodec.Decode(key, signatureLength: 64);
if (!verifier.Verify(payload, signature))      // signed bytes == recovered P
    throw new LicenseInvalidException();
var license = CanonicalPayload.Parse(payload);
Enter fullscreen mode Exit fullscreen mode

The signed bytes on the server and the verified bytes on the client are byte-identical, because both are the canonical payload. The compressor never touches the thing that is signed.

Raw DEFLATE, and the bomb guard

Use raw DEFLATE, not gzip or zlib. The gzip container costs an 18-byte header and trailer; zlib costs six. On a 200-byte payload that framing eats most of the saving. DeflateStream writes raw RFC 1951 with no framing, which is exactly what you want inside your own envelope.

static byte[] Deflate(ReadOnlySpan<byte> data)
{
    using var ms = new MemoryStream();
    using (var ds = new DeflateStream(ms, CompressionLevel.SmallestSize, leaveOpen: true))
        ds.Write(data);
    return ms.ToArray();
}

static byte[] Inflate(ReadOnlySpan<byte> data, int maxBytes)
{
    using var input = new MemoryStream(data.ToArray());
    using var ds = new DeflateStream(input, CompressionMode.Decompress);
    using var output = new MemoryStream();
    var buffer = new byte[4096];
    int total = 0, read;
    while ((read = ds.Read(buffer, 0, buffer.Length)) > 0)
    {
        total += read;
        if (total > maxBytes)
            throw new InvalidDataException("License payload too large.");
        output.Write(buffer, 0, read);
    }
    return output.ToArray();
}
Enter fullscreen mode Exit fullscreen mode

The maxBytes cap matters. A license key arrives from outside your trust boundary — a customer pastes it, or worse, an attacker submits it to your activation endpoint. A few hundred bytes of crafted DEFLATE can inflate to gigabytes. Capping the decompressed size and failing closed turns a denial-of-service into a rejected key. Verify the signature after inflation, but bound the inflation first.

CompressionLevel.SmallestSize (.NET 6+) spends more CPU to squeeze a few extra bytes out — worth it for a one-time encode on the issuing side, where throughput is not the constraint.

Grouping for humans

The final cosmetic step is breaking the Base64Url string into hyphenated groups so a person can read it back over the phone and so a line wrap does not corrupt it. Prefix a short product marker, group the rest in fives, and strip all of it on the way back in.

static string Group(string s)
{
    var sb = new StringBuilder("KR-");
    for (int i = 0; i < s.Length; i++)
    {
        if (i > 0 && i % 5 == 0) sb.Append('-');
        sb.Append(s[i]);
    }
    return sb.ToString();
}

static string Ungroup(string key) =>
    key.StartsWith("KR-", StringComparison.Ordinal)
        ? key[3..].Replace("-", "")
        : key.Replace("-", "");
Enter fullscreen mode Exit fullscreen mode

A realistic 220-byte payload full of repeated JSON keys and entitlement prefixes compresses to roughly 150 bytes. With the two header bytes and the 64-byte signature that is 216 bytes, about 288 Base64Url characters — against 380 for the uncompressed form. The customer still gets a long string, but a third shorter and one that reliably survives a copy-paste.

When it does not help

Compression is not free and not always a win. A minimal payload — a short licensee id, a tier byte, an expiry — has little redundancy, and DEFLATE's fixed overhead can make it larger. That is exactly why the encoder keeps the smaller of the two forms and records the choice in a flag bit; never assume compression shrank anything. Compression also does nothing for confidentiality: a license key is public, signed data, and anyone can inflate and read it. Keep secrets out of the payload entirely.

The real discipline is the ordering. Sign what you can reproduce, compress only the envelope, decompress before you verify, and bound the inflation. Get that sequence right and a short license key costs you nothing in trust. Get it backwards and you will ship a key that works on every machine you tested and fails on the ones you did not.

For the signing format that produces the canonical payload in the first place, see Keyright and the licensing docs.

Top comments (0)