Skip to content
← All posts
· Delta1 Labs KeyrightLicensing

Protecting a stored license at rest

A signed license already fails verification if you tamper with it — but once a client stores it on disk, you still want it bound to that machine and not casually portable. How to use Windows DPAPI (ProtectedData with CurrentUser scope), cross-platform equivalents, correct file paths and permissions, and why you re-verify the signature after decrypting.

A license file is the one artifact your protection scheme hands the user and then asks them not to touch. They can see it, copy it, and email it to a colleague. So the first instinct — “encrypt it so they can’t read it” — is aimed at the wrong threat. If the license is a signed blob, the user reading it costs you nothing, and the user editing it costs you nothing either: change one byte and the signature no longer verifies against the public key you embedded in your app. Tampering is already a solved problem.

What is not solved is portability. A signed license copied verbatim from one machine to another is still a valid signed license. If your activation flow issued it for one seat, nothing in the bytes stops it being dropped onto a second machine and loaded there. That is the gap at-rest protection closes: not “can they read it” but “will the copy they made work somewhere else.”

The real question

Where and how should a client store an activated license so that the signature still guarantees integrity, a casual copy doesn’t move the seat, and a corrupted or unreadable file never bricks the app? The answer is three independent layers — a signed blob, machine-bound confidentiality at rest, and a re-verify step on load — and the interesting part is why you need all three rather than any one.

An activated signed license is DPAPI-protected to the current user and machine, written to disk, then unprotected and signature-verified before use Activate once, then every launch reads from disk Activate signed license Protect user+machine disk ciphertext next launch Unprotect same box only Verify signature embedded pubkey Use license Protect gives confidentiality + machine-binding; it does NOT give authenticity. That is why the signature is still verified after Unprotect, every time.
The signed license is encrypted to the current user and machine with DPAPI before it touches disk, and decrypted and re-verified on every launch. Encryption binds the copy to one machine; the signature is what proves the contents are genuine.

The mechanism on Windows: DPAPI

Windows ships a data-protection API built exactly for this: encrypt a small secret so it can only be decrypted by the same user (or the same machine), without your app ever holding a key. In .NET it is System.Security.Cryptography.ProtectedData, two static methods, Protect and Unprotect. The scope flag decides the binding:

  • DataProtectionScope.CurrentUser — the ciphertext decrypts only for the user who encrypted it, on the machine where it was encrypted. This is what you want for a per-user desktop app.
  • DataProtectionScope.LocalMachine — any user on that machine can decrypt it. Use this only for a service with no interactive user; it is weaker, because every local account can read it.

Protect also takes an optional entropy argument — extra bytes mixed into the key derivation. Passing a fixed application-specific value means a blob protected by your app isn’t trivially decryptable by another app running as the same user. It is not a secret key (it ships in your binary), just additional separation.

using System.Security.Cryptography;

static class Dpapi
{
    // Application-specific salt. Not a secret; just separates our blobs from others'.
    private static readonly byte[] Entropy =
        System.Text.Encoding.UTF8.GetBytes("Keyright.LicenseStore.v1");

    public static byte[] Protect(byte[] plaintext) =>
        ProtectedData.Protect(plaintext, Entropy, DataProtectionScope.CurrentUser);

    public static byte[] Unprotect(byte[] ciphertext) =>
        ProtectedData.Unprotect(ciphertext, Entropy, DataProtectionScope.CurrentUser);
}

That is the whole Windows primitive. The key never exists in your process; the OS derives it from the user’s credentials and holds it. Copy the ciphertext to another machine and Unprotect throws a CryptographicException, because the key that produced it lives only on the original box.

A cross-platform LicenseStore

ProtectedData is Windows-only — call it on macOS or Linux and you get a PlatformNotSupportedException. A portable store wraps DPAPI on Windows and falls back elsewhere. The honest fallback is to derive a key from a stable machine identifier and encrypt with AES-GCM; on macOS the Keychain and on Linux libsecret are better homes for the key if you can take the dependency, but a machine-id-derived key keeps the same machine-binding property with no external service.

public sealed class LicenseStore
{
    private readonly string _path;

    public LicenseStore(string? appName = "Keyright")
    {
        var dir = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            appName!);
        Directory.CreateDirectory(dir);
        _path = Path.Combine(dir, "license.bin");
    }

    public void Save(byte[] signedLicense)
    {
        byte[] sealedBytes = OperatingSystem.IsWindows()
            ? Dpapi.Protect(signedLicense)
            : MachineBound.Encrypt(signedLicense);   // AES-GCM under a machine-derived key

        // Write then move, so a crash never leaves a half-written store.
        var tmp = _path + ".tmp";
        File.WriteAllBytes(tmp, sealedBytes);
        RestrictToOwner(tmp);
        File.Move(tmp, _path, overwrite: true);
    }

    public bool TryLoad(out byte[] signedLicense)
    {
        signedLicense = Array.Empty<byte>();
        if (!File.Exists(_path)) return false;
        try
        {
            byte[] raw = File.ReadAllBytes(_path);
            signedLicense = OperatingSystem.IsWindows()
                ? Dpapi.Unprotect(raw)
                : MachineBound.Decrypt(raw);
            return true;
        }
        catch (CryptographicException) { return false; } // wrong machine/user, or corrupt
        catch (IOException) { return false; }
    }

    private static void RestrictToOwner(string path)
    {
        if (OperatingSystem.IsWindows()) return; // DPAPI + ACL inheritance already scopes it
        // chmod 600 — owner read/write only
        File.SetUnixFileMode(path,
            UnixFileMode.UserRead | UnixFileMode.UserWrite);
    }
}

Two details carry real weight. The path: LocalApplicationData resolves to %LOCALAPPDATA% on Windows and ~/.local/share (or ~/Library/Application Support) elsewhere — a per-user location the app can always write, never a shared or program directory. Permissions: on Unix the file is chmod 600 so no other user can read even the ciphertext; on Windows the per-user LocalAppData path plus DPAPI already does the equivalent. The write-to-temp-then-move pattern means a crash mid-write can never corrupt a previously good store.

Verify after you load — always

The most important line is the one it is tempting to skip. DPAPI (or your AES-GCM fallback) gives you confidentiality and machine-binding. It does not give you authenticity in the sense that matters: a blob that decrypts cleanly only proves it was encrypted on this machine, not that its contents are a genuine license your server issued. The proof of genuineness is the signature, and you check it after decrypting, every single time:

public LicenseState LoadAndVerify(ILicenseVerifier verifier)
{
    if (!_store.TryLoad(out var signed))
        return LicenseState.NotActivated;   // re-activate path, not a crash

    // The verifier checks the signature offline against the embedded public key.
    LicenseState state = verifier.Verify(signed);

    // Even a valid signature can be an expired or revoked license.
    return state.IsValid ? state : LicenseState.NeedsReactivation;
}

ILicenseVerifier.Verify here is illustrative — the real call verifies the signature against the public key compiled into your app, entirely offline, and returns whether the license is valid, expired, or malformed. The ordering is the point: decrypt for confidentiality, then verify for authenticity. Skipping the verify because “it decrypted fine” trusts the wrong property.

How it fits with the server

At-rest protection is a local optimization, not the enforcement boundary. It stops a user from copying license.bin to a second laptop and having it work, and it keeps the stored contents confidential. It does not count seats, detect a shared VM image, or notice that one license is suddenly active on forty machines. That is the job of the activation/seat check your client makes against the issuing service, and of the machine fingerprint recorded at activation. At-rest storage means the common, casual case — “I’ll just copy my license file” — fails quietly on the second machine without a round trip; the server-side check is what handles the determined case and the legitimate machine move.

Caveats and when it breaks

DPAPI CurrentUser is per-user and per-machine. A user who signs in under a different Windows profile on the same PC will not be able to decrypt a store written under their old profile — so a license won’t roam across profiles. For most desktop apps that is correct behavior, but surface it in the UX: an unreadable store should route to re-activation, not an error. Roaming profiles are a sharper edge — if %LOCALAPPDATA% roams (it usually doesn’t; roaming data lives in %APPDATA%) a DPAPI blob could travel to a machine that can’t decrypt it, so keep the license store in local, non-roaming app data. VM cloning is the one that surprises teams: clone a machine with a stored license and the DPAPI key may or may not survive depending on how the image was prepared, and a machine-id-derived fallback key will change if the id changes — again, treat a decrypt failure as re-activation, and let the server decide if the clone is a new seat.

And the honest ceiling: an attacker running code as that same user can call Unprotect exactly as you do, read the plaintext license, and lift the signed blob. At-rest encryption raises the cost of casual copying and binds the stored file to one machine. It is friction and hygiene, not DRM. The security that actually enforces your terms is the signature the SDK verifies offline plus the activation check against your server.

Takeaway

Treat the three layers as doing three different jobs and you will not misuse any of them. The signature proves the license is genuine and untampered — verify it offline, every load. DPAPI with CurrentUser (or a machine-bound AES-GCM fallback) makes the stored copy confidential and non-portable — encrypt before you write, under a per-user path with owner-only permissions. The server-side activation and seat check is the real enforcement. And whatever happens to the file on disk, never hard-fail: an unreadable store means “not activated here,” and the user’s way out is to activate again. See Keyright and the documentation.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.