Skip to main content

Windows DPAPI-based encryption/decryption library for .env files

Project description

Release

EnvEncrypt

License: GPL v3 Python 3.11+ Windows 10/11

A secure environment variable management library for Windows that extends python-dotenv with automatic encryption capabilities using Windows DPAPI (Data Protection API).

Features

  • 🔒 Automatic Encryption: Seamlessly encrypts environment variables using Windows DPAPI
  • 🔄 Drop-in Replacement: Compatible with python-dotenv API
  • 📁 Dual File Support: Works with both .env and .env.enc files
  • 🚀 Background Processing: Non-blocking encryption operations
  • 💬 Comment Preservation: Maintains comments and formatting in encrypted files
  • 🔐 User-Specific Security: Encryption tied to Windows user account
  • Lazy Loading: Automatic decryption when environment variables are accessed

Installation

pip install envencrypt

Requirements:

  • Windows 10 or Windows 11
  • Python 3.11+
  • pywin32 (automatically installed)

Quick Start

Basic Usage

Replace your existing dotenv import:

# Instead of: from dotenv import load_dotenv
from envencrypt import load_dotenve

# Load and automatically encrypt values in your `.env.enc` file
load_dotenve()

Working with Encrypted Files

from envencrypt import EnvEncrypt

# Manually encrypt a .env file to .env.enc
EnvEncrypt.encrypt_env(".env", save=True)

# Decrypt and load variables from .env.enc
decrypted_vars = EnvEncrypt.decrypt_env(".env.enc")

How It Works

  1. Standard .env Loading: Loads your regular .env file using python-dotenv
  2. Encrypted .env.enc Loading: Loads your .env.enc file. In the background, encrypts sensitive values and saves them to .env.enc
  3. Secure Storage: Uses Windows DPAPI to encrypt values, tied to your user account
  4. Seamless Access: Environment variables are automatically decrypted when accessed

Encryption Format

Encrypted values in .env.enc files are prefixed with enc: followed by hex-encoded encrypted data:

# Original .env
DATABASE_PASSWORD=supersecret123
API_KEY=abc-def-ghi

# Encrypted .env.enc
DATABASE_PASSWORD=enc:01000000d08c9ddf0115d1118c7a00c04fc297eb...
API_KEY=enc:01000000d08c9ddf0115d1118c7a00c04fc297eb...

API Reference

load_dotenve()

Enhanced version of python-dotenv's load_dotenv() with encryption support.

load_dotenve(
    dotenv_path=None,              # Path to .env file (default: .env)
    encrypted_dotenv_path=None,    # Path to .env.enc file (default: .env.enc)
    verbose=False,                 # Enable verbose output (default: False)
    override=False,                # Override existing env vars from .env (default: False)
    encrypt_override=True,         # Override existing env vars from .env.enc (default: True)
    interpolate=True,              # Enable variable interpolation only for .env (default: True)
    encoding="utf-8",              # File encoding (default: utf-8)
    encrypt_in_background=True     # Encrypt .env file asynchronously (default: True)
)

[!NOTE] When encrypt_in_background=False, you must manually encrypt your .env file using the EnvEncrypt class methods shown below.

EnvEncrypt Class

Core class for encryption operations.

# Initialize
env_encrypt = EnvEncrypt(
    encrypted_dotenv_path=".env.enc",  # Path to encrypted file (default: .env.enc)
    verbose=False,                     # Enable verbose logging
    encoding="utf-8",                  # File encoding
    override=True                      # Override existing env vars
)

# Static methods
EnvEncrypt.encrypt_env(file_path, save=True)            # Encrypt a .env file and save back to same file
EnvEncrypt.encrypt_env(file_path, save=".\.env.encrypted")    # Encrypt a .env file and save to `.\.env.enc`
EnvEncrypt.decrypt_env(file_path)                       # Decrypt a .env.enc file

Security Considerations

Windows DPAPI Protection

  • User-Specific: Encrypted data can only be decrypted by the same Windows user account
  • Machine-Bound: Encryption is tied to the specific Windows machine
  • No Password Required: Uses Windows authentication, no additional passwords needed

Best Practices

  1. Exclude .env from Version Control: Add .env to .gitignore
  2. Regular Key Rotation: Periodically update sensitive credentials
  3. Access Control: Ensure proper file permissions on encrypted files

Limitations

  • Windows Only: DPAPI is Windows-specific
  • User Account Dependency: Cannot decrypt across different user accounts
  • Machine Dependency: Encrypted data cannot be moved to different machines
  • Backup Considerations: System restores may affect decryption capability

File Structure Examples

Development Workflow

project/
├── .env                 # Local development (git-ignored)
├── .env.enc            # Encrypted version 
├── .env.example        # Template file (git-tracked)
└── .gitignore          # Contains .env

Sample .env File

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
DB_USER=developer
DB_PASSWORD=secretpassword123

# API Keys
STRIPE_SECRET_KEY=sk_test_abcdef123456
JWT_SECRET=my-super-secret-jwt-key

# Optional: Empty values and comments are preserved
OPTIONAL_SETTING=
# This is a comment that will be preserved

Advanced Usage

Custom Encryption Paths

from envencrypt import load_dotenve

# Use custom paths for both files
load_dotenve(
    dotenv_path="config/.env",
    encrypted_dotenv_path="config/.env.encrypted"
)

Manual Encryption Control

from envencrypt import EnvEncrypt

# Disable background encryption
load_dotenve(encrypt_in_background=False)

# Manually encrypt when needed
EnvEncrypt.encrypt_env(".env", save=True)

Programmatic Variable Access

from envencrypt import EnvEncrypt
import os

# Load encrypted variables
load_dotenve()

# Access via os.environ (automatically decrypted)
database_password = os.environ.get("DATABASE_PASSWORD")

# Or manually decrypt specific files
decrypted_vars = EnvEncrypt.decrypt_env(".env.enc")
api_key = decrypted_vars.get("API_KEY")

Troubleshooting

Common Issues

Decryption Fails After System Changes

  • Cause: Major system changes or user account modifications
  • Solution: Re-encrypt the .env file with EnvEncrypt.encrypt_env()

Variables Not Loading

  • Check file paths and permissions
  • Verify Windows user account access
  • Enable verbose mode for debugging: load_dotenve(verbose=True)

Performance Concerns

  • Use background encryption: encrypt_in_background=True (default)
  • Consider encrypting only sensitive files manually

Debug Mode

import logging
logging.basicConfig(level=logging.DEBUG)

from envencrypt import load_dotenve
load_dotenve(verbose=True)

Contributing

Contributions are welcome! Please read our contributing guidelines and ensure all tests pass.

License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.

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

envencrypt-0.4.0.tar.gz (21.8 kB view details)

Uploaded Source

Built Distribution

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

envencrypt-0.4.0-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file envencrypt-0.4.0.tar.gz.

File metadata

  • Download URL: envencrypt-0.4.0.tar.gz
  • Upload date:
  • Size: 21.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.5

File hashes

Hashes for envencrypt-0.4.0.tar.gz
Algorithm Hash digest
SHA256 de16b1835c47d7c48afed6b55d87fed6147eb58790d2bea9bec4a4f698954082
MD5 d8a48e0137288e2a6839b481c83c66bf
BLAKE2b-256 9201e084904dc93e1e60c0650eac57620e60bd5b14b87028407849b5a4a0dce7

See more details on using hashes here.

File details

Details for the file envencrypt-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: envencrypt-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.5

File hashes

Hashes for envencrypt-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 79fa27deb9dcd4c8457a53e3944d3dff78eb1c7d6ccdd3784d7ee89b36763ac0
MD5 6bc3845f36f381103b34ed0a9f9feb71
BLAKE2b-256 79933dfb989a69c1444e181c445fbaec0ff7cae6d7b1dc651baaf0feaaf9630d

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