Py2Native Python to native compilerPython-zu-Native-Compiler

← All posts

2026-10-10

Verifying a Signed JWT License Inside a Compiled Python App

Verifying a Signed JWT License Inside a Compiled Python App
python compiler cython code protection open source

Verifying a Signed JWT License Inside a Compiled Python App

Compiling your Python to a native binary and leaving the license check as a readable Python function is a strange kind of half-measure. The code is protected, the enforcement is not. Anyone who finds your feature gate — a handful of lines comparing a string to a value, or calling out to a Python JWT library — can patch it out with a hex editor and a bit of patience.

This article covers the other half: getting the license verification itself into the compiled binary. We’ll look at what a verified license proof actually is, walk through the full workflow with Py2Native Pro, and go through the failure modes you’ll hit in production.

If you want the deeper background on why native compilation raises the bar for code protection in the first place, see Protect Python Library from Reverse Engineering: Native Compilation. Here, we stay on the verification angle.

Why License Verification Belongs Inside the Binary

Shipping proprietary software means two separate problems:

  1. Code protection — nobody should be able to read your implementation.
  2. License enforcement — only paying customers should be able to run it.

Most Python toolchains solve the first one and quietly ignore the second. That’s backwards. A license check written in Python is source code like any other:

  • It’s plain text in your distribution (or trivially recoverable from a .pyc).
  • The branch it guards can be flipped by patching a bytecode constant or monkey-patching the function it calls.
  • If it uses a third-party JWT library, an attacker doesn’t even need to understand your code — they replace the library’s verify call with one that returns True.

The fix is straightforward in principle: make the verification itself native. Py2Native compiles your custom Python to native machine code, and its Pro plugin adds signed JWT license verification on top — with the verification logic and the public key baked into the executable rather than left as Python.

You write plain Python. There’s no Cython syntax, no .pyx files to hand-author for the compilation pipeline, no manual cythonize step. The Pro plugin supplies the verification primitive; you call it.

What a Verified License Proof Looks Like

A Py2Native Pro license proof has two halves:

  • A JWT signed with an EC P-256 private key. This is the file you hand to a customer (commonly license.dat).
  • The corresponding public key, embedded into your executable at build time.

At runtime your app needs exactly one thing from the user: the token. No sidecar public key file, no network call to a license server, no config directory to populate. The public key and the ES256 verification code are compiled into the binary.

The claims you’ll validate against are:

Claim Expected value
iss (issuer) RSJ Software GmbH
aud (audience) TimestampGIT

Those two values are passed to the verification function as expected_iss and expected_aud. A token with the right signature but the wrong issuer or audience is rejected, which means a license minted for one product won’t unlock another.

Two things worth being precise about:

  • Only the public key is stored in the executable. The private key stays in your signing environment — ideally on a machine that never ships anything.
  • The elliptic curve verification is implemented in compiled code inside the plugin, with no third-party crypto libraries in the picture. That removes a whole category of “swap the dependency for a stub” attacks, because there’s no dependency to swap.

Step-by-Step: Adding JWT Verification with Py2Native Pro

1. Install the compiler and the Pro plugin

Everything goes through uv. No pip, no virtualenv juggling.

uv add py2native py2nativepro

The community package (py2native, MIT) does the compilation. py2nativepro is the proprietary plugin that adds JWT license verification and string compression.

2. Generate an EC P-256 keypair

uv run py2native keygen private.pem public.pem

This produces private.pem and public.pem. Keep private.pem out of your repository — treat it like any other signing key.

3. Create and sign the license payload

Write the claims you want to ship. At minimum, iss and aud must match what your app expects:

{
  "iss": "RSJ Software GmbH",
  "aud": "TimestampGIT",
  "sub": "acme-corp",
  "exp": 1798761600,
  "tier": "pro"
}

Then sign it:

uv run py2native sign --private private.pem payload.json license.dat

license.dat is the JWT you hand to the customer.

4. Declare the verification entry point for Cython-level access

The Pro plugin ships the declaration for the compiled verification function. In your .pxd file, the signature is declared as:

cdef _runtime_verify_es256_jwt(token, expected_iss=*, expected_aud=*)

That declaration is what makes the symbol visible to the compilation pipeline, while the implementation stays native. In the module that gates your application, import it:

from _p2n_bootstrap cimport _runtime_verify_es256_jwt

Two details matter here. token is the license string — the contents of license.dat. expected_iss and expected_aud are keyword arguments with defaults, so you can pass them explicitly per call site.

5. Call the verification function

This is the whole enforcement layer, and it compiles to native code:

from _p2n_bootstrap cimport _runtime_verify_es256_jwt


def check_license(licenseString):
    license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
    return license

On success, license holds the decoded claims — so license["tier"], license["exp"], and anything else you put in the payload is available to drive feature gating.

6. Build with the license requirement

uv run py2native build main.py *.py --license license.dat --public public.pem

The --license flag turns on the Pro license check for the build; --public embeds public.pem into the binary. Both the verification code and the key get compiled in — at runtime, your app reads the user’s token and nothing else.

If you want to inspect a token before or after shipping it:

uv run py2native show license.dat
uv run py2native show --public public.pem license.dat

The first form displays the JWT claims. Adding --public also verifies the signature against the key.

Interpreting Verification Results and Handling Edge Cases

A successful call returns the decoded claims. A failed call raises — which is what you want, because it forces you to make a decision rather than silently continuing with None.

The realistic failure modes:

  • Expired token. The exp claim is in the past. Rotate the customer’s license and reissue.
  • Wrong issuer or audience. Usually a token from a different product or a different signing environment. This is exactly why you pass expected_iss and expected_aud explicitly at every call site.
  • Tampered signature. Someone edited the payload — changing tier to enterprise, or pushing exp forward. ES256 verification catches this.
  • No token at all. The user hasn’t supplied a license file yet. This is a UX path, not a security path.
  • Corrupted or truncated key material. The build didn’t embed a usable public key, or the token was copied with a line break in the middle.

Handle it at the top of your entry point and fail closed:

from pathlib import Path

try:
    licenseString = Path("license.dat").read_text().strip()
    license = _runtime_verify_es256_jwt(licenseString, expected_iss="RSJ Software GmbH", expected_aud="TimestampGIT")
except Exception:
    print("No valid license found. Contact sales or supply license.dat.")
    raise SystemExit(1)

# Only reached with a verified token.
print(f"Licensed to {license['sub']} ({license['tier']})")

A few pragmatic notes:

  • Fail closed, always. Exit non-zero or drop into a reduced mode. Never fall through to full functionality.
  • Gate features, not just startup. A verified token lets you enable batch processing, exports, or API access selectively.
  • Remember what’s still patchable. Monkey-patching remains possible for third-party libraries, since they ship as Python source. Your compiled verification logic is not in that category — patching native code is a different order of effort.
  • Library-mode gotchas. If you build with --library, __init__.py is skipped during compilation (it’s a namespace marker) and __main__.py is excluded from sources because the wheel builder generates it. Don’t fight the tooling on those two files.

Why This Beats Manual Cython or C Extensions

There is a hard way to do this, and it’s worth naming once: hand-write a .pyx file, invoke cythonize yourself, link against OpenSSL or another crypto library, manage the build flags per platform, and keep the public key in sync with the C source. That approach works, and teams do it. It also means a build system per platform, a crypto dependency you must audit and update, and a .pyx/.pxd pair that only the person who wrote it can maintain.

Py2Native Pro hides all of it:

  • You write plain Python. The Cython invocation, C compilation, and linking are orchestrated for you.
  • You add one .pxd declaration and one cimport. That’s the entire surface area for Cython-level access.
  • The plugin handles key embedding and the verification code, so there’s no crypto library to add to your dependency tree.
  • Platform specifics are handled by the platform plugins — MSVC and PE linking on Windows, ELF linking and auditwheel repair on Linux, Mach-O on macOS.

It’s zero-config in the sense that matters: no build scripts to maintain, no manual C compilation step, no external crypto dependency to keep patched.

For the broader zero-config workflow — building an executable from plain Python without touching Cython syntax at all — see Compile Python to an Executable Without Cython Syntax. And if you’re wiring this into a release pipeline, Automating Python-to-Native Builds in CI With Py2Native covers the --license / --public flags in a CI context.

Requirements, briefly: CPython 3.11–3.15 (including free-threaded 3.14t and 3.15t), a platform C compiler (MSVC, GCC, or Clang), Windows 8+ / manylinux2014 or musl Linux / macOS, x86-64 or ARM64, and internet access during the build.

FAQ

Can I verify a JWT license without the Pro plugin?

No. The open-source core of Py2Native compiles your Python code, but signed JWT license verification is a feature of the proprietary Pro plugin. The Pro plugin bakes the ES256 verification logic and public key into your compiled binary. Without it, you’d be back to a Python-level check that anyone can patch.

What happens if someone extracts the public key from my binary?

Nothing catastrophic — the public key is not a secret. It exists to verify signatures, not to create them. Security comes from keeping the private key safe and from the fact that the verification code is compiled into the binary, making it harder to bypass than a Python-level check.

Do I need to ship the public key file with my app?

No. When you build with --public public.pem, the public key is embedded into the executable. At runtime, your app only needs the license token (e.g. license.dat) provided by the user.

Can I use my own JWT library instead of the Pro plugin?

You could, but any verification logic written in Python remains readable and patchable. Py2Native Pro compiles the verification into native code, which is significantly harder to tamper with.

Conclusion

License verification is only as strong as the layer it lives in. Put it in Python source and you’ve built a suggestion, not a gate. Put it in compiled code with the public key embedded at build time, and you’ve built something an attacker has to reverse-engineer rather than edit.

With Py2Native Pro, the whole workflow is four commands and one cimport: generate a keypair, sign a payload, call _runtime_verify_es256_jwt with your expected issuer and audience, and build with --license and --public. Your app then verifies ES256 tokens on its own, with no crypto dependency and no external files to distribute.

Ready to compile your first licensed binary? Start at py2native.dev and work through the keygen → sign → build sequence above.

Related posts

EU label: AI-generated content