Skip to main content

Cryptography Module

⚠️ WARNING: This document is not finished. The details in this document are subject to change.

The Cryptography Module is a comprehensive browser-based cryptographic library designed as a reusable microfrontend component. It provides an intuitive wrapper around the Web Crypto API, making advanced cryptographic operations accessible and easy to use in modern web applications.

📚 What Is This?

This module serves as the cryptographic foundation for the chat application, providing all the security primitives needed for:

  • End-to-end encrypted messaging using the Signal Protocol
  • Secure key exchange between peers
  • Data integrity verification with cryptographic hashing
  • Password-based encryption for local data storage
  • Random generation for unique identifiers and nonces

It's built with security, modularity, and ease of use as core principles, wrapping complex Web Crypto API operations into simple, intuitive functions.

✨ Core Features

🎲 Random Generation

  • Cryptographically Secure Random Strings: Generate unpredictable random values for security-critical operations
  • Deterministic Generation with Seeds: Reproducible randomness using Chance.js for testing and specific use cases
  • Configurable Length: Customize random string length for different purposes

#️⃣ Hashing Functions

  • SHA-256: Industry-standard 256-bit cryptographic hash
  • SHA-512: Enhanced 512-bit hash for higher security requirements
  • SHA3-512: Modern Keccak-based hash algorithm
  • Use Cases: Data integrity verification, password hashing (with salt), content addressing

🔑 Asymmetric Encryption (RSA)

  • 4096-bit RSA-OAEP: Military-grade public key cryptography
  • Key Pair Generation: Create public/private key pairs in JWK format
  • Import/Export: Seamlessly serialize and deserialize keys
  • Use Cases: Secure key exchange, digital signatures, identity verification

🔒 Symmetric Encryption (AES)

  • AES-256-GCM: Fast, authenticated encryption with integrity checking
  • Initialization Vector (IV) Management: Automatic secure IV generation
  • Password-Based Encryption: Derive encryption keys from user passwords
  • Use Cases: File encryption, bulk data encryption, local storage security

📡 Signal Protocol Implementation

  • X3DH Key Agreement: Extended Triple Diffie-Hellman for initial key exchange
  • Double Ratchet: Forward secrecy and break-in recovery for ongoing messaging
  • Ed25519 Signatures: Fast, secure digital signatures for authentication
  • X25519 Key Exchange: Elliptic curve Diffie-Hellman for perfect forward secrecy
  • Use Cases: End-to-end encrypted chat, secure P2P communication

⚡ Performance Tools

  • Algorithm Benchmarking: Compare speed of different cryptographic operations
  • Bulk Operation Testing: Measure performance under load
  • Visual Charts: Interactive performance comparisons in Storybook demos

🎨 Interactive Storybook Demos

The module includes comprehensive interactive demos showcasing all functionality:

Random Generation Stories

  • Basic cryptographically secure random generation
  • Deterministic random with custom seeds
  • Performance comparisons

Hashing Stories

  • Live hash calculator for SHA-256, SHA-512, SHA3-512
  • Hash verification tool
  • File hashing demonstrations

Asymmetric Encryption Stories

  • RSA key pair generation and management
  • Alice & Bob encryption scenario
  • Key import/export workflows

Symmetric Encryption Stories

  • Password-based file encryption
  • Bulk data encryption demos
  • Key sharing scenarios

Signal Protocol Stories

  • Complete Signal Protocol walkthrough
  • X3DH key agreement demonstration
  • Double Ratchet message encryption
  • Out-of-order message handling

Use Case Demos

  • End-to-end encrypted messaging simulation
  • File encryption tool with drag-and-drop
  • Password manager architecture demo
  • Hybrid encryption (RSA + AES) examples

Performance Benchmarks

  • Algorithm speed comparisons
  • Bulk operation metrics
  • Visual performance charts

🛠️ Usage

As a Microfrontend (Module Federation)

// In your webpack config
remotes: {
cryptography: "cryptography@https://cryptography.positive-intentions.com/remoteEntry.js"
}

// In your React component
const { useCryptography } = await import("cryptography/Cryptography");
const crypto = useCryptography();

// Use cryptographic functions
const hash = await crypto.sha256Hash("Hello World");
const keys = await crypto.generateKeyPair();
const encrypted = await crypto.encryptRSA(keys.publicKey, "Secret message");

As a React Context Provider

import { CryptographyProvider, useCryptography } from '@positive-intentions/cryptography';

function App() {
return (
<CryptographyProvider entropy="optional-custom-seed">
<YourComponents />
</CryptographyProvider>
);
}

function YourComponent() {
const crypto = useCryptography();

const handleEncrypt = async () => {
const encrypted = await crypto.encryptAES("password", "data");
console.log("Encrypted:", encrypted);
};

return <button onClick={handleEncrypt}>Encrypt</button>;
}

📦 Available Functions

The useCryptography() hook provides access to:

Random & Hashing

  • random(additionalSalt?) - Generate random strings
  • sha256Hash(input) - SHA-256 hashing
  • sha512Hash(input) - SHA-512 hashing
  • sha3_512Hash(input) - SHA3-512 hashing

RSA Operations

  • generateKeyPair() - Generate RSA-4096 key pair
  • importPublicKey(jwk) - Import public key from JWK
  • importPrivateKey(jwk) - Import private key from JWK
  • encryptRSA(publicKey, data) - Encrypt with RSA-OAEP
  • decryptRSA(privateKey, data) - Decrypt with RSA-OAEP

AES Operations

  • generateSymmetricKey() - Generate AES-256 key
  • encryptAES(password, data) - Password-based AES encryption
  • decryptAES(password, encryptedData) - Password-based AES decryption

Signal Protocol

  • initializeSignalUser(userId) - Create Signal Protocol user
  • getSignalPublicKeyBundle(user) - Export public keys for sharing
  • performSignalX3DHKeyExchange(alice, bobBundle) - X3DH key agreement
  • deriveSignalSharedSecret(...) - Derive shared secret from exchange
  • initializeDoubleRatchet(sharedSecret, isInitiator) - Start Double Ratchet
  • doubleRatchetEncrypt(state, plaintext) - Encrypt message with ratchet
  • doubleRatchetDecrypt(state, envelope) - Decrypt message with ratchet

🔐 Security Considerations

  • Browser-Based Crypto: All operations use the Web Crypto API (secure, audited by browser vendors)
  • No Server Required: Cryptography happens entirely in the browser
  • Key Storage: Keys are never sent to servers; manage them in IndexedDB or local storage
  • Forward Secrecy: Signal Protocol implementation provides forward secrecy and break-in recovery
  • Best Practices: See the blog post on P2P Signal Protocol for implementation details

🧪 Testing

The module includes comprehensive test coverage:

  • JavaScript Unit Tests: Jest-based tests for all functions
  • Rust/WASM Tests: Native Rust tests for WASM components
  • Integration Tests: End-to-end cryptographic workflow tests
  • Storybook Interaction Tests: UI component testing

Run tests:

npm test                    # JavaScript tests
npm run test:rust # Rust native tests
npm run test:wasm # WASM tests
npm run test:all:complete # All tests across platforms

🚀 Development

Local Development

# Clone the repository
git clone https://github.com/positive-intentions/cryptography.git
cd cryptography

# Install dependencies
npm install

# Start Storybook (interactive demos)
npm start
# Opens at http://localhost:6006

# Run tests
npm test

# Build for production
npm run build

Tech Stack

  • React 18 - UI framework
  • Material-UI v5 - Component library
  • Storybook 9 - Interactive component development
  • Web Crypto API - Browser cryptography
  • Rust/WASM - Optional performance-critical operations
  • Module Federation - Microfrontend architecture

📖 Learn More

🤝 Contributing

Contributions are welcome! See the GitHub repository for:

  • Code contribution guidelines
  • Issue reporting
  • Feature requests
  • Development roadmap

📄 License

Licensed under the ISC License. See LICENSE for details.


🎯 Try It Now

Explore the interactive demos to see all features in action: