Skip to main content

PyEncode

PyEncode is a pure-Python tool for protecting CPython applications on Windows and Linux. Each module is compiled to a code object, serialized with marshal, compressed, and authenticated-encrypted with AES-256-GCM. The runtime decrypts and executes the code in memory; neither plaintext source nor plaintext bytecode is written to a temporary file.

Version 0.3 uses the PYE2 format:

  • Every artifact receives a random 128-bit filename, for example myapp/7b82a40e9aa14e60db7094f2de3fbc33.pye.
  • PYE2 has no plaintext JSON header; an artifact contains only its magic value, nonce, and ciphertext/authentication tag.
  • Module names, the entry point, and package flags are stored in an encrypted module index.
  • Manifest format 3 is signed with Ed25519 and contains the SHA-256 digest of every artifact.
  • The runtime, launcher, resources, and support trees copied by the builder are all signed, key-bound, and verified again during install().
  • The loader exposes only a small trampoline to runpy, rather than returning the application's real code object. Module keys are derived on demand and are not retained by the finder.

The goal is to make static analysis substantially more expensive than it is for .pyc files. PyEncode does not claim to make reverse engineering impossible.

Supported Python versions

PyEncode 0.3 requires standard CPython 3.10 or later. CI directly tests Python 3.10 through 3.15. Newer CPython feature releases may install and build under the forward-compatible version policy, and are added to the required test matrix once the release and its dependency wheels are available. PyPy and other Python implementations are not currently supported.

The runtime is pure Python, so the same runtime source works on Windows and Linux. However, a built artifact is tied to the exact CPython major/minor version used to build it:

  • an artifact built with CPython 3.11 runs on CPython 3.11;
  • that artifact does not run on CPython 3.10, 3.12, or 3.14;
  • to support several minor versions, build a separate output with each interpreter.

If a bundle includes .pyd, .so, .dll, or other native dependencies through --support, the whole bundle is also constrained by the operating system, architecture, and ABI of those files. Current testing targets the standard GIL build of CPython; free-threaded and debug ABIs require separate builds and testing.

Installation

Install the published package from PyPI in a virtual environment:

py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install pyencode-protector

The CLI command and import namespace are both named pyencode.

For source development, use an editable installation in a virtual environment.

Windows PowerShell:

py -3.11 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e .

Linux:

python3.11 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .

The only runtime dependency is cryptography>=42.

Usage

Built-in command-line help is available without opening the documentation:

pyencode --help
pyencode build --help
python -m pyencode --help

Protect a single file:

pyencode build hello.py -o dist/hello
python dist/hello/run.py

Protect a package containing __main__.py:

pyencode build src/myapp -o dist/myapp
python dist/myapp/run.py

Specify the entry module explicitly:

pyencode build src -o dist/app --entry myapp.__main__

Sign and key-bind additional dependencies or support trees:

pyencode build src -o dist/app \
  --entry myapp.main \
  --support build/vendor _vendor \
  --support public/config.json config.json

--support SOURCE DEST may be repeated. If SOURCE is a directory, its tree is copied below DEST; if it is a file, DEST is the output file path. Symlinks, reparse points, paths that escape the root, and case-insensitive path collisions are rejected.

The exact destination _vendor is treated as a bootstrap dependency path for hosts that do not already have cryptography installed, such as Fusion. Only the exact _vendor entry remains on sys.path while the verifier loads; every other bundle subdirectory is isolated. Because the vendored cryptography library must run before Ed25519 can verify the bundle itself, _vendor is a trusted bootstrap component by design in this pure-Python runtime. Vendor only wheels obtained from trusted sources.

Main options:

  • -o, --output: output directory; it must not exist or must be completely empty.
  • -e, --entry: dotted name of the entry module or package.
  • --exclude GLOB: exclude paths matching a glob; may be repeated.
  • --no-resources: do not copy non-Python files from the source tree.
  • --keep-docstrings: preserve docstrings.
  • --optimize {0,1,2}: CPython optimization level.
  • --expires YYYY-MM-DD: refuse to run after the specified UTC date.
  • --launcher PATH: use a custom .py launcher.
  • --support SOURCE DEST: copy, sign, and key-bind a support file or tree.
  • --rename-locals: rename metadata for local variables that are not parameters.
  • --allow-extra-data: allow the host to create additional unsigned data files and directories; signed files and recognized Python/native artifact types remain protected. The application must not execute or trust the added data.

--rename-locals is opt-in because code that uses a dynamic alias of locals(), reads frame.f_locals, or depends on debugger/framework introspection may require the original local names. Arguments, closures, line tables, and exception tables are always preserved.

Custom launchers and embedded hosts

A custom launcher is copied byte-for-byte, signed, and included in key derivation. It must set:

import sys
sys.dont_write_bytecode = True

before any non-bootstrap import. The builder enforces this minimum requirement. A secure production launcher must also verify that pyencode_runtime contains no __pycache__, .pyc, or unexpected files before importing the package. The default launcher and the Weldments pipeline include the complete preflight check.

A host such as Fusion can load an entry point without placing its plaintext module name in the stub:

import sys
sys.dont_write_bytecode = True

# Perform the pyencode_runtime preflight here.
from pyencode_runtime import load_entry

implementation = load_entry()

install() intentionally returns None. load_entry() returns the entry module to an embedding host, while run() executes the entry point with __main__ semantics.

Output layout and runtime behavior

dist/app/
├── .pyencode-manifest.json
├── myapp/
│   ├── 14a0...f91c.pye
│   ├── 7b82...bc33.pye
│   └── assets/config.json
├── pyencode_runtime/
│   ├── __init__.py
│   ├── _build.py
│   ├── _mp_main.py
│   └── _runtime.py
├── requirements.txt
└── run.py

Resources are not encrypted, but their build-time bytes and paths are signed and key-bound. By default, the entire output tree is immutable: the runtime rejects any file or directory that is added, removed, or modified.

For hosts that create metadata or caches beside an add-in, --allow-extra-data permits additional data files and directories without invalidating the bundle. This mode still rejects modifications or removal of signed files, unexpected .py, .pyc, native libraries, or .pye files, and all symlinks or reparse points. Do not use this extra data as trusted input for licensing or security decisions. The Weldments pipeline enables this compatibility mode so Fusion can create .vscode, logs, or machine-specific caches.

The __file__ value of a protected module is the real path to its randomly named artifact. Consequently, Path(__file__).parent, pkgutil.get_data(), and importlib.resources, including nested directory resources, continue to work. Code that depends on the basename or stem of __file__ sees the random token.

Integration tests cover imports by full name, relative imports, circular imports, namespace packages, Unicode module names, reloads, runpy.run_module(), and multiprocessing spawn for applications launched through the default launcher. pkgutil.iter_modules() and walk_packages() cannot automatically discover protected child names because those names intentionally reside in the encrypted index; importing a known full name still works.

For an embedding host that calls load_entry(), spawning works if the child process also runs the host bootstrap. A host that places its bootstrap only inside if __name__ == '__main__' and then directly spawns a protected target requires a dedicated launcher. Automatic spawn bootstrapping currently focuses on applications executed through run().

Version 0.3 uses one fixed runtime namespace per process. Do not load two independent PyEncode distributions into the same interpreter; run them in separate processes. Randomized or multi-bundle runtime namespaces are a compatibility item to resolve before declaring a stable 1.0 API.

Security limitations

PyEncode makes static analysis harder, but it cannot guarantee secrecy on a machine fully controlled by an attacker:

  • The default mode is offline, so key material must remain in the bundle. An experienced analyst can inspect the runtime and reproduce the key-derivation process.
  • Code objects must exist in memory while they execute. Tracing, debuggers, monkeypatching, or native hooks may still observe code and runtime state.
  • The integrity interlock prevents straightforward file modification, artifact substitution, code injection, and re-signing. It does not turn a pure-Python runtime into a native trust anchor.
  • Module and entry-point names are hidden at rest, but appear during import in sys.modules, tracebacks, and runtime state. Package and resource directories may still reveal part of the application structure.
  • --expires relies on the system clock and is not a replacement for a licensing system.

Never store long-lived API keys or private keys in a client. For high-value products, the security upgrade that makes the greatest practical difference is an external or envelope key obtained from a license server or keyring. A native runtime primarily adds further reverse-engineering cost.

Testing

python -m unittest discover -v

CI runs on Windows and Ubuntu with CPython 3.10 through 3.15. Tests cover PYE2, the encrypted module index, KDF vectors, tampering and re-signing, resource/support integrity, opaque filenames, imports, packages, namespaces, Unicode, runpy, multiprocessing spawn, ordinary launchers without -B, expiration policy, and atomic output creation.

Releasing

The production release process using GitHub OIDC is documented in RELEASING.md. The workflow uploads to PyPI only when a pushed tag exactly matches the project version, for example v0.3.1.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyencode_protector-0.3.1.tar.gz (66.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyencode_protector-0.3.1-py3-none-any.whl (54.0 kB view details)

Uploaded Python 3

File details

Details for the file pyencode_protector-0.3.1.tar.gz.

File metadata

  • Download URL: pyencode_protector-0.3.1.tar.gz
  • Upload date:
  • Size: 66.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for pyencode_protector-0.3.1.tar.gz
Algorithm Hash digest
SHA256 4802a6ac9da40865167f140afcaa98744a3d95da632d283bdc83ee9ed4f028b7
MD5 2fc0803a0429b712bd4e5d7a3527e2a0
BLAKE2b-256 ceef80743e3186d05585f965469910425e73d678d045d95df696fa5122e9b265

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyencode_protector-0.3.1.tar.gz:

Publisher: release.yml on VanThanBK/pyencode

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pyencode_protector-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for pyencode_protector-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4e169e0eb90578c15653e450f9d6f2e32caec32161cec87e4bf3bfc4be286dea
MD5 91a8deb630f5b430308ab306a83c1ea6
BLAKE2b-256 23e1a59f5ba7323d6732ed482f5a0026fb1537f975ef849afde214b61edbe76c

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyencode_protector-0.3.1-py3-none-any.whl:

Publisher: release.yml on VanThanBK/pyencode

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.7.1

2 files

0.7.0

2 files

0.6.1

2 files

0.6.0

2 files

0.5.0

2 files

This release

0.3.1 This release

2 files

0.3.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page