Verify a Signed License Key Inside a Compiled Python Executable
You’ve compiled your Python into a native binary. The source is no longer sitting on disk in plain text, and shipping it feels a lot better than handing over a folder of .py files. Then someone asks the obvious question: the license check is in there too, right?
If the answer is “it’s a function in license.py that reads a key and compares strings,” you don’t really have a license check — you have a suggestion. This article walks through what it takes to verify a signed license key inside a compiled Python executable so the check runs as native code, with the public key baked into the binary. We’ll use Py2Native’s Pro plugin, because it does the part most teams get wrong: it puts the ES256 verification logic and the public key into the compiled artifact instead of leaving them in editable Python.
This article is about verification. For the signing side and general JWT handling, see the sibling post How to Sign and Verify JWT License Keys for Python Apps.
Why Verify a License Key Inside a Compiled Python Executable?
Think about the lifecycle of a typical Python license check:
- You ship source. The customer (or their contractor, or a curious user) opens the file.
- The check is something like
if not valid: sys.exit(1). - Someone deletes two lines. Done.
Even after compilation, a standalone check that lives in a separate, swappable place is a target: patch the branch, replace the module, or feed the function a token it likes. The lesson is not “encrypt harder” — it’s that the verification logic and the key material must live inside the binary that does the work, so removing the check means breaking the program.
That’s the model Py2Native’s Pro plugin implements:
- The private key never ships. Only the public key is embedded in the executable.
- The ES256 verification code is compiled into the binary, not loaded from a wheel or a third-party crypto library at runtime.
- Your job is to call the verifier from your code — you don’t write crypto, and you don’t write Cython.
Py2Native itself is the zero-config path from plain Python to a native binary: the core compiler is MIT licensed and open source, and the commercial Pro plugin (py2nativepro) layers on JWT license verification plus string compression. Everything below starts with uv run py2native.
What a Proof of License Looks Like: ES256 JWT and Baked-in Verification
A license is a signed JWT using ES256 (ECDSA over P-256). It carries claims — most importantly the issuer and audience — and it’s signed with your private key. Anyone holding the public key can check the signature; nobody holding only the public key can forge one.
During a Pro build, two things get baked into the executable:
- The public key (never the private key).
- The ES256 verification implementation, compiled natively. Per the product notes, elliptic key verification is handled with compiled code in the product itself — no third-party libraries required at runtime.
Your code reaches the verifier through the _p2n_bootstrap module that the plugin generates. You declare the signature in a .pxd file that sits next to your module:
# license_gate.pxd
from _p2n_bootstrap cimport _runtime_verify_es256_jwt
cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)
Then you call it like an ordinary function:
license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
Two things to internalize here:
- The
.pxdfile is the only “unusual” file you write. It’s a declaration, not an implementation. You are not writing C extensions, not writing.pyxlogic, and not runningcythonizeby hand. expected_issandexpected_audare your anti-reuse controls. A token minted for a different product or a different issuer fails, even if it’s validly signed.
Step-by-Step: Add License Verification to Your Compiled Python Executable
Step 1 — Generate a keypair
With the Pro plugin available in your environment, generate the EC P-256 keypair:
uv run py2native keygen private.pem public.pem
private.pem stays on your signing machine (or in your secrets manager). public.pem is the file that will be baked into builds. It is not secret.
Step 2 — Create and sign a license JWT
Write the claims you want to assert:
{
"iss": "RSJ Software GmbH",
"aud": "TimestampGIT",
"sub": "customer-4711",
"exp": 1893456000
}
Sign it with the private key:
uv run py2native sign --private private.pem payload.json license.dat
You now have license.dat, the file you ship to that customer. Whether you generate one per customer, per seat, or per contract is a business decision — the mechanics are the same.
Step 3 — Call the verifier from your code
Add the .pxd declaration shown above next to your module, and put the call behind a small gate. Here’s a module you can compile alongside the rest of your code:
# license_gate.py
from pathlib import Path
import sys
EXPECTED_ISS = "RSJ Software GmbH"
EXPECTED_AUD = "TimestampGIT"
def require_valid_license(path: str = "license.dat") -> None:
try:
licenseString = Path(path).read_text(encoding="utf-8").strip()
except OSError:
sys.exit("License file not found. Contact support for a license.")
try:
license = _runtime_verify_es256_jwt(
licenseString,
expected_iss=EXPECTED_ISS,
expected_aud=EXPECTED_AUD,
)
except Exception:
sys.exit("License verification failed. Contact support.")
if not license:
sys.exit("License is invalid or expired. Contact support.")
Wire it into your application at the point where it matters:
# main.py
from license_gate import require_valid_license
def main() -> int:
require_valid_license()
return 0
if __name__ == "__main__":
raise SystemExit(main())
The _runtime_verify_es256_jwt symbol resolves against the baked-in _p2n_bootstrap module that the Pro plugin generates during the build. Your source stays plain Python.
Step 4 — Build with the Pro plugin and the public key
uv run py2native build main.py *.py \
--public public.pem \
--license pro-license.dat \
--embed dist/myapp
A note on the two flags, because they’re easy to mix up:
--public public.pemis the key that gets baked into the executable. This is the one that matters for your customers.--licenseis the Pro build flag — per the CLI reference it requires a valid Pro license. It is your entitlement to the commercial plugin, not the per-customerlicense.datyou generated in Step 2.
Don’t confuse either with the customer token. The customer file travels next to the binary; the public key travels inside it.
You can also emit a wheel with --wheel, or a shared library with --library if you’re embedding the compiled package into another host process. In library mode the wheel ships a single compiled shared library plus a generated __init__.py (the meta-path finder that redirects import mypkg.submodule to the native lib) and a __main__.py (so python -m mypkg works). Both are generated for you.
Step 5 — Distribute
Ship dist/myapp and the customer’s license.dat. The verifier runs natively; the public key is inside the executable; there’s no Python crypto dependency to install or replace.
Interpreting Verification Results and Handling Edge Cases
_runtime_verify_es256_jwt reports failure in the two ways you’d expect from a native-checked JWT: it returns a falsey result for an invalid token, or it raises on a malformed one. Treat both as failure — that’s what the try/except plus if not license in Step 3 does.
Common edge cases worth handling deliberately:
- Missing license file. Fail with a message that tells the user what to do (“contact support for a license”), not a traceback.
- Malformed or truncated JWT. This often means a bad copy/paste or a corrupted download. Catch the exception and report it as a license problem, not an application crash.
- Expired token. The user’s contract lapsed or the clock is off. Surface a distinct message so support can triage quickly.
- Clock skew. Verifiers typically allow a small leeway. If a customer’s machine is hours off, an otherwise-valid token can fail — worth noting in your support runbook.
- Fail securely. Exit. Don’t degrade into “trial mode with a warning” unless that’s an intentional product decision, because that path is exactly what an attacker will aim for.
For debugging, the Pro plugin also ships a show command that prints the JWT claims and can verify the signature against the public key:
uv run py2native show --public public.pem license.dat
That single command answers most “my license doesn’t work” tickets: wrong iss, wrong aud, or expired.
One honest caveat: monkey-patching is still possible in general, because third-party Python libraries ship as Python source and remain replaceable. What’s not easily patched is the verification logic compiled into your binary and the key material embedded alongside it.
Best Practices for License Verification in Compiled Python
- The private key never leaves your infrastructure. It signs licenses; it does not ship. Only
public.pemgets compiled in. - Use
issandauddeliberately. Settingexpected_iss="RSJ Software GmbH"andexpected_aud="TimestampGIT"means a token from one product can’t unlock another. Pick values that are stable and specific to the product line. - Verify at a critical point, not only at startup. Startup checks are easy to skip if someone wraps your entry point. A second check before an expensive or valuable operation (export, sync, report generation) makes the gate a real part of the program’s behavior.
- Keep the
.pxdnext to the module it declares. It’s a declaration file; treating it as build trivia is how symbols go missing. - Remember the split. The core compiler (MIT) does the compilation and handles cross-platform output. The Pro plugin adds JWT license verification and string compression. If you don’t need verification, you don’t need Pro — see Python Code Protection Tools: What You Get for the Price for the tradeoffs.
FAQ
Can I verify a license without the Pro plugin?
No. The core Py2Native compiler (MIT licensed) focuses on compiling Python to native code. License verification with ES256 JWT and a baked-in public key is a feature of the commercial Pro plugin (py2nativepro).
What happens if the license is invalid or expired?
The _runtime_verify_es256_jwt function will indicate failure (e.g., by returning false or raising an exception). You should handle this in your code, typically by displaying an error and exiting.
Is the verification code visible in the binary? The public key and the verification logic are compiled into the native executable, making them difficult to extract or modify compared to plain Python source. However, no protection is absolute; the goal is to raise the bar significantly.
Do I need to write Cython code?
No. You write plain Python and use the provided .pxd file to call _runtime_verify_es256_jwt from your code. Py2Native handles the Cython compilation transparently.
Conclusion
A license check that lives in editable source is a honor-system check. A license check that lives in a compiled binary, backed by a public key and a native ES256 verifier, is a real one — and with Py2Native it costs you one .pxd file, one function call, and a build flag.
Start by compiling your project with Py2Native and confirming the binary runs. Then add the Pro plugin, generate your keypair, and move require_valid_license() into the flow where it counts.
Related posts
- Compile a Python Script to a Native Executable Without PyInstaller
- How to Sign and Verify JWT License Keys for Python Apps
- Cython vs Nuitka vs Py2Native: Which Protects Python Code?