Python Platform Guide

Complete guide for using MetaMUI Crypto Primitives with Python.

Installation

pip install metamui-crypto

Requirements

Optional Dependencies

# For development
pip install metamui-crypto[dev]

# For performance optimizations
pip install metamui-crypto[speedups]

Basic Usage

Import the Library

import metamui_crypto
from metamui_crypto import (
    # Hash functions
    SHA256, SHA512, Blake2b, Blake3,
    # Signatures
    Ed25519, Sr25519, Dilithium,
    # Encryption
    ChaCha20Poly1305, AES256,
    # Key derivation
    Argon2, PBKDF2, HKDF,
    # Post-quantum
    MLKem768, Falcon512
)

Type Hints

All functions include type hints for better IDE support:

from typing import Tuple
from metamui_crypto import Ed25519, KeyPair

def sign_message(message: bytes, keypair: KeyPair) -> bytes:
    """Sign a message with Ed25519."""
    return Ed25519.sign(message, keypair.private_key)

def verify_signature(
    signature: bytes, 
    message: bytes, 
    public_key: bytes
) -> bool:
    """Verify an Ed25519 signature."""
    return Ed25519.verify(signature, message, public_key)

Python-Specific Features

Context Managers

Use context managers for automatic cleanup of sensitive data:

from metamui_crypto import SecureBytes, ChaCha20Poly1305

# Automatic memory clearing
with SecureBytes.random(32) as key:
    cipher = ChaCha20Poly1305(key)
    ciphertext = cipher.encrypt(b"Secret message")
# key is automatically cleared here

Async Support

Async variants for I/O-heavy operations:

import asyncio
from metamui_crypto import Argon2

async def hash_password_async(password: str) -> bytes:
    # CPU-intensive operation in thread pool
    return await Argon2.hash_async(
        password,
        salt=Argon2.generate_salt(),
        memory=256*1024,
        iterations=4
    )

# Run async function
hash = asyncio.run(hash_password_async("my_password"))

Memory Views

Efficient operations with memory views:

import numpy as np
from metamui_crypto import Blake3

# Hash numpy array without copying
data = np.random.bytes(1024 * 1024)  # 1MB
hash = Blake3.hash(data.tobytes())

# Or use memory view
view = memoryview(data)
hash = Blake3.hash(view)

Streaming Operations

Process large files efficiently:

from metamui_crypto import Blake3

def hash_file(filepath: str) -> bytes:
    hasher = Blake3.new()
    
    with open(filepath, 'rb') as f:
        while chunk := f.read(8192):
            hasher.update(chunk)
    
    return hasher.finalize()

Error Handling

from metamui_crypto import CryptoError, InvalidKeyError, DecryptionError

try:
    result = some_crypto_operation()
except InvalidKeyError as e:
    print(f"Invalid key: {e}")
except DecryptionError as e:
    print(f"Decryption failed: {e}")
except CryptoError as e:
    print(f"Crypto error: {e}")

Performance Tips

1. Use Batch Operations

# Good: Batch verification
signatures = [sig1, sig2, sig3]
messages = [msg1, msg2, msg3]
public_keys = [pk1, pk2, pk3]

results = Ed25519.batch_verify(signatures, messages, public_keys)

# Slower: Individual verification
for sig, msg, pk in zip(signatures, messages, public_keys):
    Ed25519.verify(sig, msg, pk)

2. Reuse Instances

# Good: Reuse cipher instance
cipher = ChaCha20Poly1305(key)
for data in large_dataset:
    encrypted = cipher.encrypt(data)

# Slower: Create new instance each time
for data in large_dataset:
    encrypted = ChaCha20Poly1305.encrypt(data, key)

3. Use Appropriate Algorithms

# For speed: Blake3
fast_hash = Blake3.hash(data)

# For compatibility: SHA-256
compat_hash = SHA256.hash(data)

# For security: Argon2 for passwords
password_hash = Argon2.hash(password, salt)

Integration Examples

Django Integration

# settings.py
from metamui_crypto import Argon2

class MetaMUIPasswordHasher:
    def encode(self, password, salt):
        return Argon2.hash(password, salt)
    
    def verify(self, password, encoded):
        return Argon2.verify(password, encoded)

FastAPI Integration

from fastapi import FastAPI, HTTPException
from metamui_crypto import Ed25519

app = FastAPI()

@app.post("/sign")
async def sign_document(document: bytes, private_key: str):
    try:
        signature = Ed25519.sign(document, bytes.fromhex(private_key))
        return {"signature": signature.hex()}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

Jupyter Notebook Usage

# Display crypto operations nicely in notebooks
from IPython.display import display, HTML
from metamui_crypto import SHA256

def display_hash(data: bytes):
    hash = SHA256.hash(data)
    display(HTML(f"""
    <div style="font-family: monospace">
        <b>Data:</b> {data.hex()[:32]}...<br>
        <b>SHA-256:</b> {hash.hex()}
    </div>
    """))

Security Best Practices

1. Secure Random Generation

from metamui_crypto import secure_random

# Generate secure random bytes
key = secure_random(32)  # 32 bytes
nonce = secure_random(12)  # 12 bytes

2. Constant-Time Comparisons

from metamui_crypto import constant_time_compare

# Safe comparison
if constant_time_compare(computed_mac, expected_mac):
    print("MAC verified")

3. Key Derivation

from metamui_crypto import HKDF

# Derive multiple keys from master key
master_key = secure_random(32)

encryption_key = HKDF.derive(
    master_key, 
    length=32,
    info=b"encryption"
)

mac_key = HKDF.derive(
    master_key,
    length=32, 
    info=b"mac"
)

Debugging

Enable Debug Logging

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

# Now crypto operations will log details
from metamui_crypto import Ed25519
keypair = Ed25519.generate_keypair()
# Logs: "Generated Ed25519 keypair"

Verify Installation

import metamui_crypto

# Check version
print(f"Version: {metamui_crypto.__version__}")

# List available algorithms
print(f"Algorithms: {metamui_crypto.list_algorithms()}")

# Run self-tests
metamui_crypto.run_self_tests()

Next Steps