Enterprise PII Masking, Tokenization & Encryption Module
Project description
PII Engine - Enterprise PII Masking, Tokenization & Encryption Module
A production-ready, reusable module for handling PII (Personally Identifiable Information) data across all endpoints and applications. Provides enterprise-grade tokenization, encryption, masking, and pseudonymization capabilities.
๐ Quick Start
Installation
# Install the module
pip install -e .
# Install with development dependencies
pip install -e ".[dev]"
# Install with framework-specific dependencies
pip install -e ".[fastapi]" # For FastAPI integration
pip install -e ".[flask]" # For Flask integration
Basic Usage
from pii_engine import PIIEngine
# Initialize the engine
engine = PIIEngine()
# Process input data (tokenize and encrypt PII)
input_data = {
"name": "John Doe",
"email": "john.doe@company.com",
"phone": "+1-555-123-4567",
"department": "Engineering" # Non-PII field
}
processed_data = engine.process_input_data(input_data, table_name="employees")
# Result: {"name_token": "TKN_PERSON_NAME_a1b2c3d4", "email_token": "TKN_EMAIL_x9y8z7w6", ...}
# Get display data based on user role
display_data = engine.get_display_data(
processed_data,
table_name="employees",
display_mode="masked", # "masked", "pseudonymized", or "plaintext"
user_role="user"
)
# Result: {"name": "J*** D***", "email": "j***@company.com", ...}
๐๏ธ Architecture
Core Components
pii_engine/
โโโ core/
โ โโโ engine.py # Main PII Engine orchestrator
โ โโโ tokenizer.py # Deterministic tokenization
โ โโโ encryptor.py # AES-256 encryption/decryption
โ โโโ pseudonymizer.py # Fake data generation
โ โโโ masker.py # Data masking strategies
โ โโโ policy_engine.py # Policy-driven PII handling
โโโ config/
โ โโโ pii_types.py # PII type definitions
โ โโโ policies.yaml # Processing and access policies
โโโ middleware/
โ โโโ fastapi_middleware.py # FastAPI integration
โ โโโ flask_middleware.py # Flask integration
โโโ utils/
โโโ audit.py # Compliance and audit logging
Security Flow
Input Data โ Tokenization โ Encryption โ Database Storage
โ โ โ โ
"john@email.com" โ TKN_EMAIL_x9y8 โ AES-256 โ Encrypted Blob
Database Retrieval โ Decryption โ Role-based Display โ Frontend
โ โ โ โ
Encrypted Blob โ "john@email.com" โ "j***@email.com" โ User Sees Masked
๐ง Integration Examples
FastAPI Integration
from fastapi import FastAPI
from pii_engine.middleware.fastapi_middleware import PIIMiddleware
from pii_engine import PIIEngine
app = FastAPI()
pii_engine = PIIEngine()
# Add automatic PII processing middleware
app.add_middleware(
PIIMiddleware,
pii_engine=pii_engine,
auto_process_requests=True,
auto_process_responses=True
)
@app.post("/users")
async def create_user(user_data: dict):
# PII automatically processed by middleware
# Save processed_data to database
return {"status": "success"}
Flask Integration
from flask import Flask
from pii_engine.middleware.flask_middleware import PIIFlaskMiddleware
app = Flask(__name__)
pii_middleware = PIIFlaskMiddleware(app)
@app.route("/users", methods=["POST"])
@pii_process_input(table_name="users")
@pii_process_output(display_mode="masked")
def create_user(processed_data):
# Work with tokenized data
return processed_data
Manual Integration
from pii_engine import PIIEngine
def your_existing_endpoint(request_data):
engine = PIIEngine()
# Step 1: Process input PII
processed_data = engine.process_input_data(request_data, "users")
# Step 2: Save to database (contains tokens only)
database.save(processed_data)
# Step 3: Return appropriate display data
display_data = engine.get_display_data(
processed_data, "users", "masked", "user"
)
return {"user": display_data}
Standalone Proxy Service
# Run PII proxy between frontend and backend
python run_pii_proxy.py
# Frontend calls proxy instead of backend:
# http://localhost:8000/api/users (proxy)
# Proxy forwards to: http://localhost:8001/api/users (backend)
๐ก๏ธ Security Features
Multi-Layer Protection
- Tokenization: Deterministic tokens for duplicate detection
- Encryption: AES-256 Fernet encryption for data at rest
- Masking: Role-based data masking for display
- Pseudonymization: Realistic fake data for testing/analytics
- Audit Logging: Comprehensive access and operation logging
Role-Based Access Control
# config/policies.yaml
access_policies:
roles:
admin:
can_view_plaintext: true
audit_required: true
user:
can_view_masked: true
analyst:
can_view_pseudonymized: true
Compliance Support
- GDPR: Right to be forgotten, data portability
- CCPA: Opt-out rights, data transparency
- HIPAA: Healthcare data protection (configurable)
- SOX: Financial data compliance
๐ Supported PII Types
| PII Type | Tokenization | Encryption | Masking | Pseudonymization |
|---|---|---|---|---|
| โ | โ | j***@company.com |
user123@example.com |
|
| Phone | โ | โ | ******4567 |
555-123-4567 |
| Name | โ | โ | J*** D*** |
Alex Johnson |
| Address | โ | โ | 123 Main S*** |
456 Oak Ave, Springfield, CA |
| SSN | โ | โ | ***-**-6789 |
123-45-6789 |
| Credit Card | โ | โ | ****-****-****-1234 |
4532-1234-5678-9012 |
๐งช Testing
# Run all tests
pytest
# Run with coverage
pytest --cov=pii_engine --cov-report=html
# Run specific test types
pytest -m unit # Unit tests only
pytest -m integration # Integration tests only
pytest -m "not slow" # Skip slow tests
# Run security tests
pytest tests/test_security.py -v
Test Coverage Requirements
- Minimum Coverage: 90%
- Security Tests: 100% (no PII leakage)
- Integration Tests: All middleware and frameworks
- Performance Tests: Tokenization and encryption speed
๐ง Configuration
Environment Variables
# Required
PII_ENC_KEY=your-fernet-encryption-key
# Optional
PII_CONFIG_PATH=/path/to/custom/policies.yaml
PII_DB_CONNECTION_STRING=your-database-connection
PII_AUDIT_LEVEL=INFO
Generate Encryption Key
# Using the built-in key generator
pii-engine-keygen
# Or in Python
from pii_engine.core.encryptor import Encryptor
print(Encryptor.generate_key())
๐ Performance
Benchmarks
- Tokenization: ~0.5ms per field
- Encryption: ~1.0ms per field
- Decryption: ~1.2ms per field
- Masking: ~0.1ms per field
- Pseudonymization: ~0.3ms per field
Scalability
- Horizontal Scaling: Stateless design
- Database Optimization: Connection pooling, prepared statements
- Caching: Redis integration for token caching
- Bulk Operations: Efficient batch processing
๐ Production Deployment
Simple Python Service
# 1. Install the module
pip install -e .
# 2. Set encryption key
export PII_ENC_KEY="your-generated-key"
# 3. Run PII proxy service
python run_pii_proxy.py
Add to Existing Backend
from pii_engine import PIIEngine
# Add to your existing endpoints
def create_user(user_data):
engine = PIIEngine()
processed_data = engine.process_input_data(user_data, "users")
user_id = database.save(processed_data)
display_data = engine.get_display_data(processed_data, "users", "masked", "user")
return {"user": display_data}
Systemd Service (Linux)
# /etc/systemd/system/pii-proxy.service
[Unit]
Description=PII Proxy Service
After=network.target
[Service]
Type=simple
User=pii-service
WorkingDirectory=/opt/pii-engine
Environment=PII_ENC_KEY=your-key
ExecStart=/usr/bin/python3 run_pii_proxy.py
Restart=always
[Install]
WantedBy=multi-user.target
๐ Documentation
- API Documentation - Complete API reference
- Integration Guide - Framework-specific guides
- Security Guide - Security best practices
- Deployment Guide - Production deployment
- Contributing Guide - Development guidelines
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Install development dependencies (
pip install -e ".[dev]") - Setup pre-commit hooks (
pre-commit install) - Write tests for your changes
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Quality Standards
- Black formatting (88 character line length)
- isort import sorting
- flake8 linting
- mypy type checking
- bandit security scanning
- pytest testing (90%+ coverage)
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- Issues: GitHub Issues
- Documentation: Read the Docs
- Security: security@company.com
- General: platform@company.com
๐ Features
- โ Production Ready: Battle-tested in enterprise environments
- โ Framework Agnostic: Works with FastAPI, Flask, Django, and more
- โ Type Safe: Full mypy type checking support
- โ Async Support: Compatible with async/await patterns
- โ Comprehensive Testing: 90%+ test coverage
- โ Security First: No plaintext PII in databases
- โ Compliance Ready: GDPR, CCPA, HIPAA support
- โ Performance Optimized: Sub-millisecond operations
- โ Audit Trail: Complete operation logging
- โ Easy Integration: Drop-in middleware support
Made with โค๏ธ by the PII Platform Team
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pii_engine-1.0.0.tar.gz.
File metadata
- Download URL: pii_engine-1.0.0.tar.gz
- Upload date:
- Size: 43.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c13b26056f538e08fde73ec3624ac31ec498952bd58d2be6d2ace9ab2d666be7
|
|
| MD5 |
f4fa8aa11b7cb118fd981a416ec5e39f
|
|
| BLAKE2b-256 |
c9a17461eba863d92874bc6e41b276a8b78855f700a809172f684a90a5993fb3
|
File details
Details for the file pii_engine-1.0.0-py3-none-any.whl.
File metadata
- Download URL: pii_engine-1.0.0-py3-none-any.whl
- Upload date:
- Size: 41.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
48fa0a6f9723395dc01a81d489c394da7654ef8600fcf92aa37e30048ab34cf2
|
|
| MD5 |
692bccc09bd1a2b5ae5943f70a5930da
|
|
| BLAKE2b-256 |
777407803cbe97f323e97475a134aed7d8e735e32707df7475ff7cf2efcad556
|