Integration Guide

Learn how to integrate MetaMUI Crypto Primitives into your applications with real-world examples.

Quick Integration

Web Application (TypeScript)

import { ChaCha20Poly1305, Argon2, Ed25519 } from '@metamui/crypto';

// User authentication
async function authenticateUser(password: string, storedHash: string): Promise<boolean> {
    return await Argon2.verify(password, storedHash);
}

// Secure messaging
async function encryptMessage(message: string, recipientKey: Uint8Array): Promise<{
    ciphertext: Uint8Array;
    nonce: Uint8Array;
}> {
    const key = ChaCha20Poly1305.generateKey();
    const encrypted = await ChaCha20Poly1305.encrypt(
        new TextEncoder().encode(message),
        key
    );
    return encrypted;
}

Mobile App (Swift)

import MetaMUICrypto

// Secure storage
class SecureStorage {
    private let key: Data
    
    init(password: String) throws {
        // Derive key from password
        let salt = try Argon2.generateSalt()
        self.key = try Argon2.deriveKey(
            password: password,
            salt: salt,
            length: 32
        )
    }
    
    func encrypt(data: Data) throws -> Data {
        return try AES256.encrypt(data, key: key)
    }
}

Backend Service (Python)

from metamui_crypto import MLKem768, Dilithium, Blake3
import json

class SecureAPI:
    def __init__(self):
        self.signing_key = Dilithium.generate_keypair()
        self.kem_key = MLKem768.generate_keypair()
    
    def sign_response(self, data: dict) -> dict:
        """Sign API response for authenticity."""
        payload = json.dumps(data).encode()
        signature = Dilithium.sign(payload, self.signing_key.private_key)
        
        return {
            "data": data,
            "signature": signature.hex(),
            "public_key": self.signing_key.public_key.hex()
        }

Common Integration Patterns

1. Secure Communication

Build end-to-end encrypted communication:

# Hybrid encryption for messages
from metamui_crypto import X25519, ChaCha20Poly1305

class SecureChannel:
    def __init__(self):
        self.keypair = X25519.generate_keypair()
    
    def encrypt_for(self, message: bytes, recipient_public_key: bytes) -> dict:
        # Generate ephemeral keypair
        ephemeral = X25519.generate_keypair()
        
        # Compute shared secret
        shared_secret = X25519.compute_shared_secret(
            ephemeral.private_key,
            recipient_public_key
        )
        
        # Encrypt with shared secret
        ciphertext, nonce = ChaCha20Poly1305.encrypt(
            message,
            shared_secret[:32]
        )
        
        return {
            "ephemeral_public": ephemeral.public_key,
            "ciphertext": ciphertext,
            "nonce": nonce
        }

2. Password Management

Secure password storage and verification:

from metamui_crypto import Argon2, secure_random
import base64

class PasswordManager:
    @staticmethod
    def hash_password(password: str) -> str:
        """Hash password for storage."""
        salt = secure_random(16)
        hash = Argon2.hash(
            password.encode(),
            salt,
            memory=256*1024,  # 256MB
            iterations=4,
            parallelism=2
        )
        # Store salt with hash
        return base64.b64encode(salt + hash).decode()
    
    @staticmethod
    def verify_password(password: str, stored_hash: str) -> bool:
        """Verify password against stored hash."""
        data = base64.b64decode(stored_hash)
        salt = data[:16]
        hash = data[16:]
        
        computed = Argon2.hash(
            password.encode(),
            salt,
            memory=256*1024,
            iterations=4,
            parallelism=2
        )
        return constant_time_compare(computed, hash)

3. File Encryption

Encrypt files with streaming:

from metamui_crypto import ChaCha20Poly1305, Blake3
import os

class FileEncryptor:
    def __init__(self, key: bytes):
        self.cipher = ChaCha20Poly1305(key)
    
    def encrypt_file(self, input_path: str, output_path: str):
        """Encrypt file with authentication."""
        # Generate file ID
        file_id = Blake3.hash(os.urandom(16))
        
        with open(input_path, 'rb') as infile, \
             open(output_path, 'wb') as outfile:
            
            # Write header
            nonce = self.cipher.generate_nonce()
            outfile.write(file_id)
            outfile.write(nonce)
            
            # Encrypt in chunks
            while chunk := infile.read(64 * 1024):  # 64KB chunks
                encrypted = self.cipher.encrypt_chunk(chunk, nonce)
                outfile.write(encrypted)

4. Blockchain Integration

Post-quantum secure blockchain:

from metamui_crypto import Dilithium, Blake3, MLKem768
import time

class QuantumResistantBlock:
    def __init__(self, data: dict, previous_hash: bytes):
        self.timestamp = time.time()
        self.data = data
        self.previous_hash = previous_hash
        self.nonce = 0
        self.hash = self.calculate_hash()
    
    def calculate_hash(self) -> bytes:
        """Calculate block hash."""
        block_data = f"{self.timestamp}{self.data}{self.previous_hash}{self.nonce}"
        return Blake3.hash(block_data.encode())
    
    def sign_block(self, private_key: bytes) -> bytes:
        """Sign block with post-quantum signature."""
        return Dilithium.sign(self.hash, private_key)

Framework Integration

Django

# settings.py
INSTALLED_APPS = [
    'metamui_crypto.django',
    # ...
]

# Custom password hasher
PASSWORD_HASHERS = [
    'metamui_crypto.django.Argon2PasswordHasher',
    # ...
]

# models.py
from metamui_crypto.django import EncryptedField

class SecureModel(models.Model):
    sensitive_data = EncryptedField()

FastAPI

from fastapi import FastAPI, Depends
from metamui_crypto import Ed25519

app = FastAPI()

async def verify_signature(
    signature: str,
    message: str,
    public_key: str
):
    """Dependency for signature verification."""
    try:
        is_valid = Ed25519.verify(
            bytes.fromhex(signature),
            message.encode(),
            bytes.fromhex(public_key)
        )
        if not is_valid:
            raise HTTPException(401, "Invalid signature")
    except Exception:
        raise HTTPException(400, "Bad request")

@app.post("/secure-endpoint")
async def secure_endpoint(
    data: dict,
    verified: None = Depends(verify_signature)
):
    return {"status": "verified", "data": data}

React Native

import { MLKem768, AES256 } from '@metamui/crypto-wasm';

// Secure storage hook
export function useSecureStorage() {
    const [isReady, setIsReady] = useState(false);
    
    useEffect(() => {
        // Initialize WASM module
        initializeCrypto().then(() => setIsReady(true));
    }, []);
    
    const encryptData = useCallback(async (data: any) => {
        if (!isReady) throw new Error('Crypto not initialized');
        
        const key = await AES256.generateKey();
        const encrypted = await AES256.encrypt(
            JSON.stringify(data),
            key
        );
        
        // Store encrypted data
        await AsyncStorage.setItem('secure_data', encrypted);
        await Keychain.setInternetCredentials(
            'app_key',
            'key',
            key
        );
    }, [isReady]);
    
    return { encryptData, isReady };
}

Testing

Unit Tests

import pytest
from metamui_crypto import ChaCha20Poly1305

def test_encryption_decryption():
    key = ChaCha20Poly1305.generate_key()
    plaintext = b"Test message"
    
    # Encrypt
    ciphertext, nonce = ChaCha20Poly1305.encrypt(plaintext, key)
    
    # Decrypt
    decrypted = ChaCha20Poly1305.decrypt(ciphertext, nonce, key)
    
    assert decrypted == plaintext

def test_tampering_detection():
    key = ChaCha20Poly1305.generate_key()
    ciphertext, nonce = ChaCha20Poly1305.encrypt(b"Test", key)
    
    # Tamper with ciphertext
    tampered = bytearray(ciphertext)
    tampered[0] ^= 1
    
    # Should raise exception
    with pytest.raises(DecryptionError):
        ChaCha20Poly1305.decrypt(bytes(tampered), nonce, key)

Performance Optimization

Batch Operations

# Process multiple items efficiently
signatures = Ed25519.batch_sign(messages, private_key)
results = Ed25519.batch_verify(signatures, messages, public_keys)

Parallel Processing

import asyncio
from concurrent.futures import ThreadPoolExecutor

async def parallel_encrypt(items: list, key: bytes):
    """Encrypt items in parallel."""
    loop = asyncio.get_event_loop()
    
    with ThreadPoolExecutor() as executor:
        tasks = [
            loop.run_in_executor(
                executor,
                ChaCha20Poly1305.encrypt,
                item,
                key
            )
            for item in items
        ]
        
        return await asyncio.gather(*tasks)

Next Steps