Example Applications

Complete example applications demonstrating MetaMUI Crypto Primitives in real-world scenarios.

🔐 Secure Messaging App

TypeScript/React Frontend

Complete end-to-end encrypted messaging application.

// src/crypto/MessageCrypto.ts
import { X25519, ChaCha20Poly1305, Ed25519, Blake3 } from '@metamui/crypto';

export class SecureMessaging {
    private keypair: Ed25519.KeyPair;
    private dhKeypair: X25519.KeyPair;

    constructor() {
        this.keypair = Ed25519.generateKeyPair();
        this.dhKeypair = X25519.generateKeyPair();
    }

    // Generate message ID
    private generateMessageId(): string {
        const randomBytes = crypto.getRandomValues(new Uint8Array(16));
        return Blake3.hash(randomBytes).toString('hex').slice(0, 16);
    }

    // Encrypt message for recipient
    async encryptMessage(
        message: string, 
        recipientPublicKey: Uint8Array,
        metadata?: any
    ): Promise<EncryptedMessage> {
        // Generate ephemeral key for forward secrecy
        const ephemeralKeypair = X25519.generateKeyPair();
        
        // Compute shared secret
        const sharedSecret = X25519.computeSharedSecret(
            ephemeralKeypair.privateKey,
            recipientPublicKey
        );

        // Derive encryption key
        const encryptionKey = Blake3.deriveKey(
            sharedSecret,
            'MetaMUI-Message-v1',
            32
        );

        // Prepare message data
        const messageData = {
            content: message,
            timestamp: Date.now(),
            metadata: metadata || {},
            sender: this.keypair.publicKey
        };

        const plaintext = new TextEncoder().encode(JSON.stringify(messageData));
        
        // Encrypt message
        const encrypted = await ChaCha20Poly1305.encrypt(plaintext, encryptionKey);
        
        // Sign the encrypted message
        const signature = Ed25519.sign(
            encrypted.ciphertext,
            this.keypair.privateKey
        );

        return {
            id: this.generateMessageId(),
            ephemeralPublicKey: ephemeralKeypair.publicKey,
            ciphertext: encrypted.ciphertext,
            nonce: encrypted.nonce,
            signature,
            senderPublicKey: this.keypair.publicKey
        };
    }

    // Decrypt received message
    async decryptMessage(
        encryptedMessage: EncryptedMessage
    ): Promise<DecryptedMessage> {
        // Verify signature first
        const signatureValid = Ed25519.verify(
            encryptedMessage.signature,
            encryptedMessage.ciphertext,
            encryptedMessage.senderPublicKey
        );

        if (!signatureValid) {
            throw new Error('Invalid message signature');
        }

        // Compute shared secret
        const sharedSecret = X25519.computeSharedSecret(
            this.dhKeypair.privateKey,
            encryptedMessage.ephemeralPublicKey
        );

        // Derive decryption key
        const decryptionKey = Blake3.deriveKey(
            sharedSecret,
            'MetaMUI-Message-v1',
            32
        );

        // Decrypt message
        const decrypted = await ChaCha20Poly1305.decrypt(
            encryptedMessage.ciphertext,
            encryptedMessage.nonce,
            decryptionKey
        );

        const messageData = JSON.parse(new TextDecoder().decode(decrypted));

        return {
            id: encryptedMessage.id,
            content: messageData.content,
            timestamp: messageData.timestamp,
            metadata: messageData.metadata,
            sender: messageData.sender,
            verified: true
        };
    }
}

// React component
export function SecureChat() {
    const [messages, setMessages] = useState<DecryptedMessage[]>([]);
    const [messageCrypto] = useState(() => new SecureMessaging());
    const [currentMessage, setCurrentMessage] = useState('');

    const sendMessage = async (recipientKey: Uint8Array) => {
        try {
            const encrypted = await messageCrypto.encryptMessage(
                currentMessage,
                recipientKey,
                { type: 'text' }
            );

            // Send to server/peer
            await sendToRecipient(encrypted);
            setCurrentMessage('');
        } catch (error) {
            console.error('Failed to send message:', error);
        }
    };

    return (
        <div className="secure-chat">
            <div className="messages">
                {messages.map(msg => (
                    <div key={msg.id} className="message">
                        <span className="timestamp">
                            {new Date(msg.timestamp).toLocaleTimeString()}
                        </span>
                        <span className="content">{msg.content}</span>
                        {msg.verified && <span className="verified"></span>}
                    </div>
                ))}
            </div>
            <div className="input-area">
                <input
                    value={currentMessage}
                    onChange={(e) => setCurrentMessage(e.target.value)}
                    placeholder="Type your message..."
                />
                <button onClick={() => sendMessage(recipientPublicKey)}>
                    Send Encrypted
                </button>
            </div>
        </div>
    );
}

Python Backend

WebSocket server for real-time encrypted messaging.

# server/secure_messaging_server.py
import asyncio
import websockets
import json
from typing import Dict, Set
from metamui_crypto import X25519, ChaCha20Poly1305, Ed25519, Blake3

class SecureMessagingServer:
    def __init__(self):
        self.connected_clients: Dict[str, websockets.WebSocketServerProtocol] = {}
        self.client_public_keys: Dict[str, bytes] = {}

    async def register_client(self, websocket, public_key: str):
        """Register a new client connection."""
        client_id = Blake3.hash(public_key.encode()).hex()[:16]
        
        self.connected_clients[client_id] = websocket
        self.client_public_keys[client_id] = bytes.fromhex(public_key)
        
        await websocket.send(json.dumps({
            'type': 'registered',
            'client_id': client_id
        }))
        
        return client_id

    async def relay_message(self, sender_id: str, recipient_id: str, encrypted_message: dict):
        """Relay encrypted message between clients."""
        if recipient_id not in self.connected_clients:
            return False

        recipient_socket = self.connected_clients[recipient_id]
        
        # Add sender information
        message_with_sender = {
            'type': 'encrypted_message',
            'sender_id': sender_id,
            'message': encrypted_message
        }
        
        try:
            await recipient_socket.send(json.dumps(message_with_sender))
            return True
        except websockets.exceptions.ConnectionClosed:
            # Clean up disconnected client
            del self.connected_clients[recipient_id]
            if recipient_id in self.client_public_keys:
                del self.client_public_keys[recipient_id]
            return False

    async def handle_client(self, websocket, path):
        """Handle individual client connections."""
        client_id = None
        try:
            async for message in websocket:
                try:
                    data = json.loads(message)
                    
                    if data['type'] == 'register':
                        client_id = await self.register_client(
                            websocket, 
                            data['public_key']
                        )
                    
                    elif data['type'] == 'send_message':
                        if client_id:
                            success = await self.relay_message(
                                client_id,
                                data['recipient_id'],
                                data['encrypted_message']
                            )
                            
                            await websocket.send(json.dumps({
                                'type': 'message_status',
                                'success': success
                            }))
                    
                    elif data['type'] == 'get_online_users':
                        await websocket.send(json.dumps({
                            'type': 'online_users',
                            'users': list(self.connected_clients.keys())
                        }))
                        
                except json.JSONDecodeError:
                    await websocket.send(json.dumps({
                        'type': 'error',
                        'message': 'Invalid JSON'
                    }))
                    
        except websockets.exceptions.ConnectionClosed:
            pass
        finally:
            # Clean up on disconnect
            if client_id and client_id in self.connected_clients:
                del self.connected_clients[client_id]
                if client_id in self.client_public_keys:
                    del self.client_public_keys[client_id]

# Run server
async def main():
    server = SecureMessagingServer()
    
    print("Starting secure messaging server on ws://localhost:8765")
    start_server = websockets.serve(server.handle_client, "localhost", 8765)
    
    await start_server
    await asyncio.Future()  # Run forever

if __name__ == "__main__":
    asyncio.run(main())

🏦 Secure Banking API

FastAPI Backend with Post-Quantum Security

Complete banking API with quantum-resistant cryptography.

# banking_api/secure_banking.py
from fastapi import FastAPI, HTTPException, Depends, Header
from fastapi.security import HTTPBearer
from pydantic import BaseModel
from typing import Optional, List
import asyncio
from datetime import datetime, timedelta
import jwt

from metamui_crypto import (
    MLKem768, Dilithium, Falcon512, ChaCha20Poly1305, 
    Argon2, Blake3, secure_random
)

app = FastAPI(title="Quantum-Secure Banking API")
security = HTTPBearer()

class BankingCrypto:
    def __init__(self):
        # Bank's master keypairs for different purposes
        self.kem_keypair = MLKem768.generate_keypair()
        self.signature_keypair = Dilithium.generate_keypair() 
        self.fast_signature_keypair = Falcon512.generate_keypair()
        
        # Session encryption key (rotated periodically)
        self.session_key = ChaCha20Poly1305.generate_key()

class TransactionRequest(BaseModel):
    from_account: str
    to_account: str
    amount: float
    description: str
    encrypted_data: str  # Additional encrypted details

class Account(BaseModel):
    account_id: str
    balance: float
    owner_public_key: str

class SecureTransaction(BaseModel):
    transaction_id: str
    from_account: str
    to_account: str
    amount: float
    timestamp: datetime
    signature: str
    encrypted_details: str

banking_crypto = BankingCrypto()

# Database simulation
accounts_db: Dict[str, Account] = {}
transactions_db: List[SecureTransaction] = []

def verify_account_signature(
    account_id: str, 
    message: bytes, 
    signature: str,
    public_key: str
) -> bool:
    """Verify account holder's signature."""
    try:
        return Falcon512.verify(
            bytes.fromhex(signature),
            message,
            bytes.fromhex(public_key)
        )
    except Exception:
        return False

async def get_current_user(authorization: str = Header(...)):
    """Extract and verify user from JWT token."""
    try:
        token = authorization.replace("Bearer ", "")
        # In production, verify JWT with bank's public key
        payload = jwt.decode(token, "secret", algorithms=["HS256"])
        return payload["account_id"]
    except:
        raise HTTPException(401, "Invalid authentication")

@app.post("/api/v1/accounts/create")
async def create_account(
    owner_public_key: str,
    initial_deposit: float = 0.0
):
    """Create new quantum-secure account."""
    if initial_deposit < 0:
        raise HTTPException(400, "Invalid initial deposit")
    
    # Generate unique account ID
    account_data = f"{owner_public_key}{datetime.now().isoformat()}"
    account_id = Blake3.hash(account_data.encode()).hex()[:16]
    
    # Create account
    account = Account(
        account_id=account_id,
        balance=initial_deposit,
        owner_public_key=owner_public_key
    )
    
    accounts_db[account_id] = account
    
    # Sign account creation with bank's signature
    account_json = account.json().encode()
    creation_signature = Dilithium.sign(
        account_json,
        banking_crypto.signature_keypair.private_key
    )
    
    return {
        "account": account,
        "creation_signature": creation_signature.hex(),
        "bank_public_key": banking_crypto.signature_keypair.public_key.hex()
    }

@app.post("/api/v1/transactions/create")
async def create_transaction(
    transaction: TransactionRequest,
    user_signature: str,
    current_user: str = Depends(get_current_user)
):
    """Create quantum-secure transaction."""
    
    # Verify user owns the from_account
    if current_user != transaction.from_account:
        raise HTTPException(403, "Can only transfer from your own account")
    
    # Check account exists and has sufficient balance
    if transaction.from_account not in accounts_db:
        raise HTTPException(404, "From account not found")
    
    from_account = accounts_db[transaction.from_account]
    if from_account.balance < transaction.amount:
        raise HTTPException(400, "Insufficient balance")
    
    # Verify transaction signature
    transaction_data = f"{transaction.from_account}{transaction.to_account}{transaction.amount}"
    if not verify_account_signature(
        transaction.from_account,
        transaction_data.encode(),
        user_signature,
        from_account.owner_public_key
    ):
        raise HTTPException(401, "Invalid transaction signature")
    
    # Create secure transaction
    transaction_id = Blake3.hash(
        f"{transaction_data}{datetime.now().isoformat()}".encode()
    ).hex()[:16]
    
    # Encrypt sensitive transaction details
    encrypted_details = ChaCha20Poly1305.encrypt(
        transaction.encrypted_data.encode(),
        banking_crypto.session_key
    )
    
    secure_txn = SecureTransaction(
        transaction_id=transaction_id,
        from_account=transaction.from_account,
        to_account=transaction.to_account,
        amount=transaction.amount,
        timestamp=datetime.now(),
        signature=user_signature,
        encrypted_details=encrypted_details.ciphertext.hex()
    )
    
    # Update balances
    accounts_db[transaction.from_account].balance -= transaction.amount
    if transaction.to_account in accounts_db:
        accounts_db[transaction.to_account].balance += transaction.amount
    
    # Sign transaction with bank's fast signature
    txn_hash = Blake3.hash(secure_txn.json().encode())
    bank_signature = Falcon512.sign(
        txn_hash,
        banking_crypto.fast_signature_keypair.private_key
    )
    
    transactions_db.append(secure_txn)
    
    return {
        "transaction": secure_txn,
        "bank_signature": bank_signature.hex(),
        "transaction_hash": txn_hash.hex()
    }

@app.get("/api/v1/accounts/{account_id}/balance")
async def get_balance(
    account_id: str,
    current_user: str = Depends(get_current_user)
):
    """Get account balance with cryptographic proof."""
    if current_user != account_id:
        raise HTTPException(403, "Can only view your own balance")
    
    if account_id not in accounts_db:
        raise HTTPException(404, "Account not found")
    
    account = accounts_db[account_id]
    
    # Create cryptographic proof of balance
    balance_data = f"{account_id}{account.balance}{datetime.now().isoformat()}"
    balance_signature = Dilithium.sign(
        balance_data.encode(),
        banking_crypto.signature_keypair.private_key
    )
    
    return {
        "account_id": account_id,
        "balance": account.balance,
        "timestamp": datetime.now(),
        "proof_signature": balance_signature.hex(),
        "bank_public_key": banking_crypto.signature_keypair.public_key.hex()
    }

@app.get("/api/v1/transactions/history/{account_id}")
async def get_transaction_history(
    account_id: str,
    current_user: str = Depends(get_current_user)
):
    """Get transaction history for account."""
    if current_user != account_id:
        raise HTTPException(403, "Can only view your own transactions")
    
    # Filter transactions for this account
    account_transactions = [
        txn for txn in transactions_db 
        if txn.from_account == account_id or txn.to_account == account_id
    ]
    
    # Sign the transaction history
    history_data = json.dumps([txn.dict() for txn in account_transactions])
    history_signature = Dilithium.sign(
        history_data.encode(),
        banking_crypto.signature_keypair.private_key
    )
    
    return {
        "account_id": account_id,
        "transactions": account_transactions,
        "history_signature": history_signature.hex(),
        "count": len(account_transactions)
    }

@app.post("/api/v1/key-exchange")
async def establish_secure_session(client_public_key: str):
    """Establish quantum-secure session with client."""
    try:
        client_key = bytes.fromhex(client_public_key)
        
        # Perform ML-KEM key encapsulation
        ciphertext, shared_secret = MLKem768.encapsulate(
            client_key,
            banking_crypto.kem_keypair.public_key
        )
        
        # Derive session key
        session_key = Blake3.deriveKey(
            shared_secret,
            'BankingSession-v1',
            32
        )
        
        # Store session key (in production, use secure session storage)
        session_id = Blake3.hash(shared_secret).hex()[:16]
        
        return {
            "session_id": session_id,
            "ciphertext": ciphertext.hex(),
            "bank_kem_public_key": banking_crypto.kem_keypair.public_key.hex()
        }
        
    except Exception as e:
        raise HTTPException(400, f"Key exchange failed: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

📱 Mobile Wallet App (Swift)

iOS Quantum-Resistant Wallet

Complete mobile wallet with MetaMUI cryptography.

// WalletCrypto.swift
import Foundation
import MetaMUICrypto

class QuantumWallet: ObservableObject {
    private let keychain = Keychain(service: "com.metamui.wallet")
    
    @Published var isUnlocked = false
    @Published var balance: Double = 0.0
    @Published var transactions: [Transaction] = []
    
    private var masterKey: Data?
    private var signingKeypair: Falcon512.KeyPair?
    private var kemKeypair: MLKem768.KeyPair?
    
    struct Transaction {
        let id: String
        let amount: Double
        let recipient: String
        let timestamp: Date
        let signature: Data
        let isConfirmed: Bool
    }
    
    // Initialize wallet with biometric protection
    func initializeWallet(password: String) async throws {
        // Derive master key from password
        let salt = try keychain.getData("wallet_salt") ?? {
            let newSalt = SecureRandom.generateBytes(32)
            try keychain.set(newSalt, key: "wallet_salt")
            return newSalt
        }()
        
        masterKey = try await Argon2.deriveKey(
            password: password,
            salt: salt,
            memorySize: 256 * 1024, // 256MB
            iterations: 4,
            parallelism: 2,
            keyLength: 32
        )
        
        // Generate or restore cryptographic keys
        try await restoreOrGenerateKeys()
        
        isUnlocked = true
        await loadTransactions()
    }
    
    private func restoreOrGenerateKeys() async throws {
        guard let masterKey = masterKey else {
            throw WalletError.notInitialized
        }
        
        // Try to restore existing keys
        if let encryptedSigningKey = try? keychain.getData("signing_key"),
           let encryptedKemKey = try? keychain.getData("kem_key") {
            
            // Decrypt stored keys
            let signingKeyData = try ChaCha20Poly1305.decrypt(
                encryptedSigningKey,
                key: masterKey
            )
            let kemKeyData = try ChaCha20Poly1305.decrypt(
                encryptedKemKey,
                key: masterKey
            )
            
            signingKeypair = try Falcon512.KeyPair(privateKey: signingKeyData)
            kemKeypair = try MLKem768.KeyPair(privateKey: kemKeyData)
            
        } else {
            // Generate new keys
            signingKeypair = Falcon512.generateKeyPair()
            kemKeypair = MLKem768.generateKeyPair()
            
            // Encrypt and store keys
            let encryptedSigningKey = try ChaCha20Poly1305.encrypt(
                signingKeypair!.privateKey,
                key: masterKey
            )
            let encryptedKemKey = try ChaCha20Poly1305.encrypt(
                kemKeypair!.privateKey,
                key: masterKey
            )
            
            try keychain.set(encryptedSigningKey, key: "signing_key")
            try keychain.set(encryptedKemKey, key: "kem_key")
        }
    }
    
    // Create quantum-secure transaction
    func createTransaction(
        amount: Double,
        recipientAddress: String,
        description: String
    ) async throws -> Transaction {
        guard let signingKeypair = signingKeypair else {
            throw WalletError.notInitialized
        }
        
        // Create transaction data
        let transactionId = UUID().uuidString
        let timestamp = Date()
        
        let transactionData = TransactionData(
            id: transactionId,
            amount: amount,
            recipient: recipientAddress,
            sender: getWalletAddress(),
            timestamp: timestamp,
            description: description
        )
        
        // Serialize transaction
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        let transactionBytes = try encoder.encode(transactionData)
        
        // Create quantum-resistant signature
        let signature = try Falcon512.sign(
            message: transactionBytes,
            privateKey: signingKeypair.privateKey
        )
        
        let transaction = Transaction(
            id: transactionId,
            amount: amount,
            recipient: recipientAddress,
            timestamp: timestamp,
            signature: signature,
            isConfirmed: false
        )
        
        // Add to pending transactions
        transactions.append(transaction)
        
        // Submit to network
        try await submitTransaction(transaction)
        
        return transaction
    }
    
    // Verify received transaction
    func verifyTransaction(_ transaction: Transaction, senderPublicKey: Data) throws -> Bool {
        let transactionData = TransactionData(
            id: transaction.id,
            amount: transaction.amount,
            recipient: getWalletAddress(),
            sender: "", // Will be verified separately
            timestamp: transaction.timestamp,
            description: ""
        )
        
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        let transactionBytes = try encoder.encode(transactionData)
        
        return try Falcon512.verify(
            signature: transaction.signature,
            message: transactionBytes,
            publicKey: senderPublicKey
        )
    }
    
    // Secure key exchange with another wallet
    func establishSecureChannel(peerPublicKey: Data) async throws -> SecureChannel {
        guard let kemKeypair = kemKeypair else {
            throw WalletError.notInitialized
        }
        
        // Perform ML-KEM encapsulation
        let encapsulationResult = try MLKem768.encapsulate(
            publicKey: peerPublicKey
        )
        
        // Derive communication key
        let channelKey = try Blake3.deriveKey(
            inputKey: encapsulationResult.sharedSecret,
            context: "WalletChannel-v1",
            length: 32
        )
        
        return SecureChannel(
            sessionKey: channelKey,
            ciphertext: encapsulationResult.ciphertext
        )
    }
    
    // Backup wallet with encryption
    func createEncryptedBackup(password: String) async throws -> Data {
        guard let signingKeypair = signingKeypair,
              let kemKeypair = kemKeypair else {
            throw WalletError.notInitialized
        }
        
        // Create backup data structure
        let backup = WalletBackup(
            signingPrivateKey: signingKeypair.privateKey,
            kemPrivateKey: kemKeypair.privateKey,
            transactions: transactions,
            createdAt: Date()
        )
        
        // Serialize backup
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        let backupData = try encoder.encode(backup)
        
        // Derive backup encryption key
        let salt = SecureRandom.generateBytes(32)
        let backupKey = try await Argon2.deriveKey(
            password: password,
            salt: salt,
            memorySize: 512 * 1024, // Higher security for backup
            iterations: 8,
            parallelism: 4,
            keyLength: 32
        )
        
        // Encrypt backup
        let encryptedBackup = try ChaCha20Poly1305.encrypt(
            backupData,
            key: backupKey
        )
        
        // Combine salt + encrypted data
        var finalBackup = Data()
        finalBackup.append(salt)
        finalBackup.append(encryptedBackup)
        
        return finalBackup
    }
    
    // Restore wallet from encrypted backup
    func restoreFromBackup(_ backupData: Data, password: String) async throws {
        guard backupData.count > 32 else {
            throw WalletError.invalidBackup
        }
        
        // Extract salt and encrypted data
        let salt = backupData.prefix(32)
        let encryptedData = backupData.dropFirst(32)
        
        // Derive backup decryption key
        let backupKey = try await Argon2.deriveKey(
            password: password,
            salt: Data(salt),
            memorySize: 512 * 1024,
            iterations: 8,
            parallelism: 4,
            keyLength: 32
        )
        
        // Decrypt backup
        let decryptedData = try ChaCha20Poly1305.decrypt(
            Data(encryptedData),
            key: backupKey
        )
        
        // Deserialize backup
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        let backup = try decoder.decode(WalletBackup.self, from: decryptedData)
        
        // Restore keys and data
        signingKeypair = try Falcon512.KeyPair(privateKey: backup.signingPrivateKey)
        kemKeypair = try MLKem768.KeyPair(privateKey: backup.kemPrivateKey)
        transactions = backup.transactions
        
        isUnlocked = true
        
        // Re-encrypt and store with current master key
        try await restoreOrGenerateKeys()
    }
    
    func getWalletAddress() -> String {
        guard let signingKeypair = signingKeypair else { return "" }
        
        // Create address from public key hash
        let publicKeyHash = Blake3.hash(signingKeypair.publicKey)
        return "mq" + publicKeyHash.prefix(20).base58EncodedString()
    }
    
    private func submitTransaction(_ transaction: Transaction) async throws {
        // Submit to blockchain network
        // Implementation depends on specific blockchain
    }
    
    private func loadTransactions() async {
        // Load transaction history from blockchain
        // Implementation depends on specific blockchain
    }
}

// SwiftUI Views
struct WalletView: View {
    @StateObject private var wallet = QuantumWallet()
    @State private var showingUnlock = true
    @State private var password = ""
    
    var body: some View {
        NavigationView {
            if wallet.isUnlocked {
                WalletHomeView()
                    .environmentObject(wallet)
            } else {
                UnlockView(password: $password) {
                    Task {
                        try await wallet.initializeWallet(password: password)
                    }
                }
            }
        }
    }
}

struct WalletHomeView: View {
    @EnvironmentObject var wallet: QuantumWallet
    
    var body: some View {
        VStack(spacing: 20) {
            // Balance Card
            VStack {
                Text("Balance")
                    .font(.headline)
                Text("$\(wallet.balance, specifier: "%.2f")")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                Text("Quantum Secured")
                    .font(.caption)
                    .foregroundColor(.green)
            }
            .padding()
            .background(Color.gray.opacity(0.1))
            .cornerRadius(12)
            
            // Quick Actions
            HStack(spacing: 15) {
                Button("Send") {
                    // Show send view
                }
                .buttonStyle(.borderedProminent)
                
                Button("Receive") {
                    // Show receive view
                }
                .buttonStyle(.bordered)
                
                Button("Backup") {
                    // Show backup view
                }
                .buttonStyle(.bordered)
            }
            
            // Recent Transactions
            List(wallet.transactions, id: \.id) { transaction in
                TransactionRow(transaction: transaction)
            }
        }
        .navigationTitle("MetaMUI Wallet")
        .padding()
    }
}

🔒 Password Manager

Rust CLI Password Manager

Command-line password manager with quantum-resistant security.

// src/main.rs
use metamui_crypto::{
    Argon2, ChaCha20Poly1305, Blake3, SecureRandom,
    Falcon512, MLKem768
};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use rpassword::read_password;

#[derive(Parser)]
#[command(name = "quantum-pass")]
#[command(about = "Quantum-resistant password manager")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize new password vault
    Init,
    /// Add new password entry
    Add {
        /// Service name
        service: String,
        /// Username
        username: String,
    },
    /// Get password for service
    Get {
        /// Service name
        service: String,
    },
    /// List all services
    List,
    /// Generate secure password
    Generate {
        /// Password length
        #[arg(default_value_t = 32)]
        length: usize,
    },
    /// Export encrypted vault
    Export {
        /// Output file path
        output: PathBuf,
    },
    /// Import encrypted vault
    Import {
        /// Input file path
        input: PathBuf,
    },
}

#[derive(Serialize, Deserialize)]
struct PasswordEntry {
    service: String,
    username: String,
    password: String,
    created_at: chrono::DateTime<chrono::Utc>,
    notes: Option<String>,
}

#[derive(Serialize, Deserialize)]
struct PasswordVault {
    entries: HashMap<String, PasswordEntry>,
    created_at: chrono::DateTime<chrono::Utc>,
    version: u32,
}

struct QuantumPasswordManager {
    vault_path: PathBuf,
    master_key: Option<[u8; 32]>,
}

impl QuantumPasswordManager {
    fn new() -> Self {
        let home_dir = dirs::home_dir().expect("Could not find home directory");
        let vault_path = home_dir.join(".quantum-pass").join("vault.enc");
        
        Self {
            vault_path,
            master_key: None,
        }
    }

    fn initialize_vault(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Create directory if it doesn't exist
        if let Some(dir) = self.vault_path.parent() {
            fs::create_dir_all(dir)?;
        }

        println!("Initializing quantum-resistant password vault...");
        print!("Enter master password: ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let master_password = read_password()?;

        print!("Confirm master password: ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let confirm_password = read_password()?;

        if master_password != confirm_password {
            return Err("Passwords do not match".into());
        }

        // Generate salt
        let salt = SecureRandom::generate_bytes(32);
        
        // Derive master key with Argon2
        let master_key = Argon2::derive_key(
            master_password.as_bytes(),
            &salt,
            512 * 1024, // 512MB memory
            8,          // 8 iterations
            4,          // 4 parallel threads
            32,         // 32-byte key
        )?;

        self.master_key = Some(master_key.try_into().unwrap());

        // Create empty vault
        let vault = PasswordVault {
            entries: HashMap::new(),
            created_at: chrono::Utc::now(),
            version: 1,
        };

        // Encrypt and save vault
        self.save_vault(&vault)?;

        // Save salt separately
        let salt_path = self.vault_path.with_extension("salt");
        fs::write(salt_path, salt)?;

        println!("Vault initialized successfully!");
        Ok(())
    }

    fn unlock_vault(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if !self.vault_path.exists() {
            return Err("Vault not found. Run 'quantum-pass init' first.".into());
        }

        print!("Enter master password: ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let master_password = read_password()?;

        // Load salt
        let salt_path = self.vault_path.with_extension("salt");
        let salt = fs::read(salt_path)?;

        // Derive master key
        let master_key = Argon2::derive_key(
            master_password.as_bytes(),
            &salt,
            512 * 1024,
            8,
            4,
            32,
        )?;

        self.master_key = Some(master_key.try_into().unwrap());

        // Try to decrypt vault to verify password
        self.load_vault()?;

        println!("Vault unlocked successfully!");
        Ok(())
    }

    fn add_password(&self, service: String, username: String) -> Result<(), Box<dyn std::error::Error>> {
        let mut vault = self.load_vault()?;

        print!("Enter password (or press Enter to generate): ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let password = read_password()?;

        let password = if password.is_empty() {
            self.generate_password(32)?
        } else {
            password
        };

        let entry = PasswordEntry {
            service: service.clone(),
            username,
            password: password.clone(),
            created_at: chrono::Utc::now(),
            notes: None,
        };

        vault.entries.insert(service.clone(), entry);
        self.save_vault(&vault)?;

        println!("Password added for service: {}", service);
        println!("Generated password: {}", password);
        Ok(())
    }

    fn get_password(&self, service: String) -> Result<(), Box<dyn std::error::Error>> {
        let vault = self.load_vault()?;

        if let Some(entry) = vault.entries.get(&service) {
            println!("Service: {}", entry.service);
            println!("Username: {}", entry.username);
            println!("Password: {}", entry.password);
            println!("Created: {}", entry.created_at.format("%Y-%m-%d %H:%M:%S UTC"));
        } else {
            println!("No entry found for service: {}", service);
        }

        Ok(())
    }

    fn list_services(&self) -> Result<(), Box<dyn std::error::Error>> {
        let vault = self.load_vault()?;

        if vault.entries.is_empty() {
            println!("No password entries found.");
            return Ok(());
        }

        println!("Stored password entries:");
        for (service, entry) in vault.entries.iter() {
            println!("  {} ({})", service, entry.username);
        }

        Ok(())
    }

    fn generate_password(&self, length: usize) -> Result<String, Box<dyn std::error::Error>> {
        const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        
        let random_bytes = SecureRandom::generate_bytes(length);
        let password: String = random_bytes
            .iter()
            .map(|&byte| CHARSET[byte as usize % CHARSET.len()] as char)
            .collect();

        println!("Generated password: {}", password);
        Ok(password)
    }

    fn export_vault(&self, output_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
        let vault = self.load_vault()?;
        
        // Serialize vault
        let vault_json = serde_json::to_vec_pretty(&vault)?;
        
        print!("Enter export password: ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let export_password = read_password()?;

        // Generate export salt
        let salt = SecureRandom::generate_bytes(32);
        
        // Derive export key
        let export_key = Argon2::derive_key(
            export_password.as_bytes(),
            &salt,
            256 * 1024, // 256MB for export
            4,
            2,
            32,
        )?;

        // Encrypt vault
        let encrypted_vault = ChaCha20Poly1305::encrypt(
            &vault_json,
            &export_key.try_into().unwrap(),
        )?;

        // Combine salt + encrypted data
        let mut export_data = Vec::new();
        export_data.extend_from_slice(&salt);
        export_data.extend_from_slice(&encrypted_vault.ciphertext);
        export_data.extend_from_slice(&encrypted_vault.nonce);

        fs::write(output_path, export_data)?;
        println!("Vault exported successfully!");
        Ok(())
    }

    fn import_vault(&mut self, input_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
        let import_data = fs::read(input_path)?;
        
        if import_data.len() < 32 + 12 {
            return Err("Invalid import file".into());
        }

        // Extract components
        let salt = &import_data[0..32];
        let nonce = &import_data[import_data.len()-12..];
        let ciphertext = &import_data[32..import_data.len()-12];

        print!("Enter import password: ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let import_password = read_password()?;

        // Derive import key
        let import_key = Argon2::derive_key(
            import_password.as_bytes(),
            salt,
            256 * 1024,
            4,
            2,
            32,
        )?;

        // Decrypt vault
        let decrypted_data = ChaCha20Poly1305::decrypt(
            ciphertext,
            nonce,
            &import_key.try_into().unwrap(),
        )?;

        // Deserialize vault
        let imported_vault: PasswordVault = serde_json::from_slice(&decrypted_data)?;

        // Merge with current vault
        let mut current_vault = if self.vault_path.exists() {
            self.load_vault()?
        } else {
            PasswordVault {
                entries: HashMap::new(),
                created_at: chrono::Utc::now(),
                version: 1,
            }
        };

        for (service, entry) in imported_vault.entries {
            current_vault.entries.insert(service, entry);
        }

        self.save_vault(&current_vault)?;
        println!("Vault imported successfully!");
        Ok(())
    }

    fn load_vault(&self) -> Result<PasswordVault, Box<dyn std::error::Error>> {
        let master_key = self.master_key.ok_or("Vault not unlocked")?;
        
        let encrypted_data = fs::read(&self.vault_path)?;
        let decrypted_data = ChaCha20Poly1305::decrypt_raw(&encrypted_data, &master_key)?;
        
        let vault: PasswordVault = serde_json::from_slice(&decrypted_data)?;
        Ok(vault)
    }

    fn save_vault(&self, vault: &PasswordVault) -> Result<(), Box<dyn std::error::Error>> {
        let master_key = self.master_key.ok_or("Vault not unlocked")?;
        
        let vault_json = serde_json::to_vec(vault)?;
        let encrypted_data = ChaCha20Poly1305::encrypt_raw(&vault_json, &master_key)?;
        
        fs::write(&self.vault_path, encrypted_data)?;
        Ok(())
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    let mut password_manager = QuantumPasswordManager::new();

    match cli.command {
        Commands::Init => {
            password_manager.initialize_vault()?;
        }
        Commands::Add { service, username } => {
            password_manager.unlock_vault()?;
            password_manager.add_password(service, username)?;
        }
        Commands::Get { service } => {
            password_manager.unlock_vault()?;
            password_manager.get_password(service)?;
        }
        Commands::List => {
            password_manager.unlock_vault()?;
            password_manager.list_services()?;
        }
        Commands::Generate { length } => {
            password_manager.generate_password(length)?;
        }
        Commands::Export { output } => {
            password_manager.unlock_vault()?;
            password_manager.export_vault(output)?;
        }
        Commands::Import { input } => {
            password_manager.import_vault(input)?;
        }
    }

    Ok(())
}

Next Steps

These examples demonstrate MetaMUI’s capabilities in real-world applications:

Additional Resources