Skip to main content

Python-based command line tool to encrypt and decrypt Python modules.

Project description

Python Encrypt Code

Python 3.12+ License: MIT

A tool that integrates seamlessly with modern CI and Dockerized edge deployments.

A powerful Python CLI tool for encrypting and decrypting Python modules, enabling secure distribution and execution of Python code. Perfect for protecting intellectual property, distributing commercial Python applications, or creating secure deployment packages.

โš ๏ธ SECURITY DISCLAIMER: This tool is currently in development and not ready for production use. In its current version, the tool writes decrypted files to temporary directories on disk during execution, which poses a security risk as sensitive code may remain accessible in the filesystem. This security vulnerability will be addressed in a future version by implementing in-memory execution. Use at your own risk for development and testing purposes only.

Features

  • ๐Ÿ” Strong Encryption: AES-256 encryption using the cryptography library
  • ๐Ÿ“ฆ Module Packaging: Compress and encrypt entire Python packages into a single encrypted file
  • ๐Ÿš€ Direct Execution: Run encrypted Python modules without extracting to disk (coming in a later version)
  • ๐Ÿ”‘ Secure Password Generation: Built-in cryptographically secure password generator
  • ๐Ÿ› ๏ธ Developer Friendly: Full type annotations and comprehensive test coverage
  • ๐Ÿ“ Preserve Structure: Maintains package hierarchy and imports when decrypting

Installation

Using uv (recommended)

git clone https://gitea.gt-proj.com/brian/python-encrypt-code.git
cd python-encrypt-code
uv install

Using pip

git clone https://gitea.gt-proj.com/brian/python-encrypt-code.git
cd python-encrypt-code
pip install -e .

Quick Start

1. Generate a Secure Password

uv run python-encrypt-code generate-password
# Output: Wlg2aFQ2dWhkX0U0TkxOcXBHY09acTR1ZVo5UlNPcWxSamVxOTI5a08tdz0=

2. Encrypt a Python Module

export MODULE_PATH=./src/my_package
export ENCRYPTED_FILE=my_package.pec
export PASSWORD=your-secure-password

uv run python-encrypt-code encrypt ${MODULE_PATH} -o ${ENCRYPTED_FILE} -p ${PASSWORD}

3. Decrypt an Encrypted File

uv run python-encrypt-code decrypt ${ENCRYPTED_FILE} -o ./decrypted -p ${PASSWORD}

4. Run Encrypted Module Directly

uv run python-encrypt-code run-insecure ${ENCRYPTED_FILE} --script main.py

Commands

generate-password

Generate a cryptographically secure password for encryption.

uv run python-encrypt-code generate-password

encrypt

Encrypt a Python module or package directory.

uv run python-encrypt-code encrypt <source> -o <output> -p <password> [-aad <json-string>]

Options:

  • source_path: Directory containing Python files to encrypt
  • -o, --output: Output path for encrypted file
  • -p, --password: Password for encryption
  • -aad, --additional-authenticated-data: JSON-formatted string to embed metadata in the encrypted file

decrypt

Decrypt a file and extract contents to disk.

uv run python-encrypt-code decrypt <source> -o <output>

Options:

  • source: Path to encrypted file
  • -o, --output: Directory to extract decrypted files

run-insecure

Decrypt and execute a Python script from an encrypted package. N.B. this writes decrypted files to a temporary folder on the disk before executing!

uv run python-encrypt-code run-insecure <source> --script <script>

Options:

  • source: Path to encrypted file
  • -s, --script: Python script to execute

Use Cases

1. Protecting Commercial Python Applications

# Encrypt your entire application
export PASSWORD=$(uv run python-encrypt-code generate-password)
uv run python-encrypt-code encrypt ./my_app -o my_app.pec -p ${PASSWORD}

# Setup your own authentication source and subclass the PasswordProvider
# Distribute the .pec file to customers and
# let them run it without seeing the source code
uv run python-encrypt-code run-insecure ./my_app.pec -p ${PASSWORD} --script main.py

2. Secure Deployment Packages

# Create encrypted deployment package
uv run python-encrypt-code encrypt ./production_code -o deployment.pec -p $DEPLOY_PASSWORD

# Deploy and run on target server
uv run python-encrypt-code run-insecure deployment.pec --script startup.py

3. Educational Content Protection

# Protect course materials or assignments
uv run python-encrypt-code encrypt ./course_solutions -o solutions.pec -p student_password

Development

Prerequisites

  • Python 3.12+
  • uv (recommended) or pip

Setup Development Environment

git clone https://github.com/yourusername/python-encrypt-code.git
cd python-encrypt-code

# Install with development dependencies
uv install --dev

# Install pre-commit hooks
uv run pre-commit install

Project Structure

python-encrypt-code/
โ”œโ”€โ”€ src/python_encrypt_code/          # Main package
โ”‚   โ”œโ”€โ”€ __main__.py                   # CLI entry point
โ”‚   โ”œโ”€โ”€ data_zipper/                  # Compression utilities
โ”‚   โ”œโ”€โ”€ file_encrypter/               # Encryption/decryption
โ”‚   โ”œโ”€โ”€ password_provider/            # Password generation
โ”‚   โ””โ”€โ”€ module_importer/              # Dynamic module loading
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ unit/                         # Unit tests
โ”‚   โ”œโ”€โ”€ integration/                  # Integration tests
โ”‚   โ””โ”€โ”€ test_data/                    # Test fixtures
โ”œโ”€โ”€ pyproject.toml                    # Project configuration
โ””โ”€โ”€ README.md

Running Tests

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov-report=term-missing --cov=src/python_encrypt_code

# Run specific test categories
uv run pytest tests/unit/           # Unit tests only
uv run pytest tests/integration/    # Integration tests only

Code Quality

# Type checking
uv run mypy .

# Linting and formatting
uv run ruff check .
uv run ruff format .
uv run prettier --write .

# Run pre-commit checks
uv run pre-commit run --all-files

Technical Details

Encryption Method

  • Algorithm: AES-256-GCM (Galois/Counter Mode)
  • Key Format: Direct 32-byte key from base64-encoded password
  • Authentication: Built-in authentication tag prevents tampering
  • Nonce: Random 12-byte nonce for each encryption operation

File Format

Encrypted .pec files contain:

  1. Nonce (12 bytes)
  2. Encrypted ZIP archive with authentication tag (variable length)

Module Loading

The ModuleImporter class provides sophisticated module loading capabilities:

  • Preserves package structure and relative imports
  • Handles __init__.py files correctly
  • Supports running specific scripts from encrypted packages
  • Temporary filesystem isolation for security

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (uv run pytest)
  6. Run code quality checks (uv run pre-commit run --all-files)
  7. Commit your changes (git commit -m 'Add amazing feature')
  8. Push to the branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

Security Considerations

  • Password Storage: Never store passwords in plain text. Use environment variables or secure key management systems.
  • Direct Key Usage: Uses base64-encoded 32-byte keys directly with AES-256-GCM (no key derivation).
  • Memory Safety: Temporary decrypted files are automatically cleaned up.
  • Verification: Authentication tags prevent tampering with encrypted files.
  • Custom Password Providers: For production deployments, you should implement your own PasswordProvider class adapted to your specific security architecture (e.g., integration with HSMs, key vaults, or enterprise secret management systems). Custom implementations can collect available metadata such as user context, machine identifiers, environment variables, or request timestamps and send this information along with password requests to your secret management system for enhanced security and audit logging. The default implementation is suitable for development and testing only.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v0.1.0

  • Initial release
  • Basic encrypt/decrypt functionality
  • CLI interface with all core commands
  • Comprehensive test suite
  • Type annotations and documentation

Support

  • ๐Ÿ› Bug Reports: Open an issue
  • ๐Ÿ’ก Feature Requests: Open an issue
  • ๐Ÿ“– Documentation: See inline documentation and type hints
  • ๐Ÿค Contributing: See Contributing section above

Coming Soon

  • Implement key derivation: improve user friendliness as well as brute-force protection
  • Support pure in-memory execution: improves security

Project details


Download files

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

Source Distribution

python_encrypt_code-0.1.1.tar.gz (69.9 kB view details)

Uploaded Source

Built Distribution

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

python_encrypt_code-0.1.1-py3-none-any.whl (19.6 kB view details)

Uploaded Python 3

File details

Details for the file python_encrypt_code-0.1.1.tar.gz.

File metadata

  • Download URL: python_encrypt_code-0.1.1.tar.gz
  • Upload date:
  • Size: 69.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.13

File hashes

Hashes for python_encrypt_code-0.1.1.tar.gz
Algorithm Hash digest
SHA256 9517e8af7351714fc9ee64335148519e6afad034e747520916e84a417dd40a34
MD5 1c808ad0041d351d9adff2b6f1c5b316
BLAKE2b-256 3eebdbfd8bf0cfaf15fc0fc92db62e0ddaa6634db45fa7d14ac4ba80a9b598ad

See more details on using hashes here.

File details

Details for the file python_encrypt_code-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for python_encrypt_code-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 750ff5a15437d7c1b90eaf5d45f55134e63056ae5de8282f4e7623101940b00c
MD5 0cc16ac703ce0e83f8309f99d539cf79
BLAKE2b-256 98dfb5d84911ecdd78d9a7aeff8d19d0a46ce1e58bdbdb52b2f6891ea3876f4f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page