UNPKG

qclair-quantshield-react-native-android

Version:

🛡️ Post-quantum encryption for React Native Android apps. ML-KEM + AES-GCM encryption with automatic proxy routing and key rotation. (Android only - iOS coming soon)

431 lines (315 loc) 12.5 kB
# 🛡️ QuantShield React Native > Post-quantum encryption SDK for React Native Android applications [![npm version](https://img.shields.io/npm/v/qclair-quantshield-react-native-android)](https://www.npmjs.com/package/qclair-quantshield-react-native-android) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Platform](https://img.shields.io/badge/platform-Android-green.svg)](https://www.android.com/) Secure your React Native Android app with **ML-KEM-1024** (post-quantum) key exchange and **AES-256-GCM** encryption. ## ✨ Features - 🔐 **Post-Quantum Security** - ML-KEM-1024 (FIPS 203) key encapsulation - 🔒 **AES-256-GCM Encryption** - Authenticated encryption with associated data - 🚀 **Easy Integration** - Just 3 methods to use - ⚡ **Native Performance** - Powered by BouncyCastle crypto library - 🔄 **Automatic Proxy Routing** - All HTTP requests automatically routed through QuantShield proxy - 📱 **Android Support** - API 21+ (Android 5.0+) ## 📋 Requirements - React Native >= 0.60.0 - Android API >= 21 (Android 5.0+) - Node.js >= 16 ## 🚀 Installation ```bash npm install qclair-quantshield-react-native-android ``` The package includes all dependencies - no additional setup required! ## 📖 Quick Start ### 1. Initialize ```typescript import QuantShield from 'qclair-quantshield-react-native-android'; // Option 1: Use fetch() for HTTP requests (recommended) await QuantShield.initialize('https://your-server.com', { autoProtect: true, // Auto-intercept fetch() calls (default: true) allowedDomains: ['api.example.com'] // Optional: only intercept these domains }); // Option 2: Use Axios (requires XHR patching) await QuantShield.initialize('https://your-server.com', { autoProtect: true, patchXHR: true, // Enable XMLHttpRequest patching for Axios allowedDomains: ['api.example.com'] }); console.log('QuantShield initialized!'); ``` ### 2. Encrypt Data ```typescript // Encrypt data const encrypted = await QuantShield.encryptData('Hello World'); console.log('Encrypted:', encrypted); ``` ### 3. Decrypt Data ```typescript // Decrypt data const decrypted = await QuantShield.decryptData(encrypted); console.log('Decrypted:', decrypted); ``` ## � How Proxy Routing Works When `autoProtect: true` is enabled, QuantShield automatically intercepts all HTTP requests: **Before QuantShield:** ```javascript fetch('https://api.example.com/users') // → Direct to api.example.com ``` **After QuantShield:** ```javascript fetch('https://api.example.com/users') // → Intercepted and routed to: // https://your-server.com/decrypt-and-forward // (with X-Original-URL: https://api.example.com/users) ``` Your QuantShield server acts as a proxy that: 1. Receives encrypted requests from the client 2. Decrypts the request body 3. Forwards to the original destination 4. Encrypts the response 5. Returns encrypted response to client ## �📚 Complete Example ```typescript import React, { useEffect, useState } from 'react'; import { View, Text, Button, Alert } from 'react-native'; import QuantShield from 'qclair-quantshield-react-native-android'; export default function App() { const [initialized, setInitialized] = useState(false); useEffect(() => { initializeQuantShield(); }, []); const initializeQuantShield = async () => { try { const result = await QuantShield.initialize('https://your-server.com', { autoProtect: true, // Auto-encrypt fetch() calls allowedDomains: ['api.example.com'] }); console.log('✅ Initialized! UID:', result.uid); // Optional: Enable automatic key rotation QuantShield.enableAutoRefresh(10); // Refresh every 10 minutes setInitialized(true); } catch (error) { console.error('❌ Initialization failed:', error); } }; const testEncryption = async () => { try { // Encrypt const plainText = 'My secret message'; const encrypted = await QuantShield.encryptData(plainText); console.log('Encrypted:', encrypted); // Decrypt const decrypted = await QuantShield.decryptData(encrypted); console.log('Decrypted:', decrypted); Alert.alert('Success!', `Original: ${plainText}\nDecrypted: ${decrypted}`); } catch (error) { Alert.alert('Error', error.message); } }; return ( <View style={{ flex: 1, justifyContent: 'center', padding: 20 }}> <Text style={{ fontSize: 20, marginBottom: 20, textAlign: 'center' }}> QuantShield Demo </Text> {initialized ? ( <Button title="Test Encryption" onPress={testEncryption} /> ) : ( <Text style={{ textAlign: 'center' }}>Initializing...</Text> )} </View> ); } ``` ## 🔧 API Reference ### `initialize(serverUrl, options?)` Initialize QuantShield and perform ML-KEM-1024 handshake. ```typescript const result = await QuantShield.initialize('https://server.com', { autoProtect: true, // Auto-encrypt fetch() calls (default: true) patchXHR: false, // Enable XMLHttpRequest patching for Axios (default: false) allowedDomains: [] // Domains to intercept (empty = all domains) }); ``` **Options:** - `autoProtect` (boolean): Automatically intercept and encrypt HTTP requests. Default: `true` - `patchXHR` (boolean): Enable XMLHttpRequest patching for Axios/XHR-based libraries. Default: `false` - Set to `false` if using only `fetch()` (recommended) - Set to `true` if using Axios or other XHR-based HTTP clients - `allowedDomains` (string[]): List of domains to intercept. Empty array = intercept all domains. **Returns:** ```typescript { success: boolean; // Handshake success uid: string; // Session UID cached: boolean; // Whether session was restored from cache } ``` **Important:** - By default, only `fetch()` is patched to avoid conflicts with fetch polyfills - Enable `patchXHR: true` only if you're using Axios or other XMLHttpRequest-based libraries - Don't mix `fetch()` and Axios if both patches are enabled - use one or the other ### `encryptData(data)` Encrypt string data with AES-256-GCM. ```typescript const encrypted = await QuantShield.encryptData('Hello World'); ``` **Returns:** `string` (Base64 URL-safe encrypted data) ### `decryptData(encryptedData)` Decrypt string data with AES-256-GCM. ```typescript const decrypted = await QuantShield.decryptData(encrypted); ``` **Returns:** `string` (Decrypted plain text) ### `getStatus()` Get current initialization status. ```typescript const status = await QuantShield.getStatus(); // { initialized: boolean, hasSessionKey: boolean, uid: string } ``` ### `reset()` Clear stored keys and reset state. ```typescript await QuantShield.reset(); ``` ## 🔄 Automatic Key Rotation Enable automatic key refresh to rotate encryption keys periodically for enhanced security. ### `enableAutoRefresh(intervalMinutes?)` Start automatic key rotation at specified intervals. ```typescript // Enable auto-refresh every 10 minutes (default) QuantShield.enableAutoRefresh(10); // Or customize the interval QuantShield.enableAutoRefresh(5); // Every 5 minutes QuantShield.enableAutoRefresh(30); // Every 30 minutes ``` **Parameters:** - `intervalMinutes` (optional): Number of minutes between key refreshes. Default: 10 **Example with React Native lifecycle:** ```typescript import React, { useEffect } from 'react'; import QuantShield from 'qclair-quantshield-react-native-android'; export default function App() { useEffect(() => { // Initialize QuantShield const init = async () => { await QuantShield.initialize('https://your-proxy.com', { autoProtect: true, allowedDomains: ['api.example.com'] }); // Enable auto-refresh after initialization QuantShield.enableAutoRefresh(10); }; init(); // Cleanup on unmount return () => { QuantShield.disableAutoRefresh(); }; }, []); return <YourApp />; } ``` ### `disableAutoRefresh()` Stop automatic key rotation. ```typescript QuantShield.disableAutoRefresh(); ``` **Benefits of Auto-Refresh:** - ✅ **Enhanced Security**: Fresh encryption keys at regular intervals - ✅ **Reduced Attack Window**: Compromised keys have limited validity - ✅ **Non-Blocking**: Runs in background without interrupting requests - ✅ **Automatic**: No manual intervention required - ✅ **Safe**: Prevents concurrent refreshes **Note**: Each refresh generates a new UID and encryption key. The old session is replaced seamlessly. ## 🌐 Auto HTTP Interception When `autoProtect: true` (default), HTTP requests are automatically encrypted/decrypted. ### Using fetch() (Recommended) ```typescript // Initialize with fetch support (default) await QuantShield.initialize('https://server.com', { autoProtect: true // patchXHR defaults to false }); // All fetch calls are now encrypted automatically! const response = await fetch('https://api.example.com/data', { method: 'POST', body: JSON.stringify({ message: 'Hello' }) }); // ↑ Request body is encrypted before sending // ↓ Response is decrypted before returning const data = await response.json(); console.log(data); // Decrypted data ``` ### Using Axios (Requires XHR Patching) ```typescript import axios from 'axios'; // Initialize with XHR patching for Axios await QuantShield.initialize('https://server.com', { autoProtect: true, patchXHR: true // Enable XMLHttpRequest patching }); // Axios requests are now encrypted automatically! const response = await axios.post('https://api.example.com/data', { message: 'Hello' }); console.log(response.data); // Decrypted data ``` ### Important Notes - **fetch() vs Axios**: Choose one approach for your app - Use `fetch()` if possible (native, modern, default support) - Use `patchXHR: true` only if you need Axios or other XHR-based libraries - Don't enable `patchXHR` if using only `fetch()` to avoid conflicts - **Selective Interception**: Use `allowedDomains` to intercept specific domains only ```typescript await QuantShield.initialize('https://server.com', { autoProtect: true, allowedDomains: ['api.example.com', 'secure-api.com'] }); ``` ## 🔐 Security ### Cryptographic Algorithms - **Key Exchange:** ML-KEM-1024 (Module-Lattice-Based KEM, FIPS 203) - **Encryption:** AES-256-GCM (Galois/Counter Mode) - **Key Derivation:** HKDF-SHA256 (RFC 5869) - **Library:** BouncyCastle 1.78 ### Post-Quantum Security ML-KEM (formerly CRYSTALS-Kyber) is a **NIST-standardized** post-quantum cryptographic algorithm designed to be secure against attacks by quantum computers. ## 🛠️ Troubleshooting ### Android Build Issues If you encounter build issues: ```bash cd android ./gradlew clean cd .. npm run android ``` ### Module Not Found Ensure auto-linking is working: ```bash npx react-native-clean-project npm install ``` For manual linking (React Native < 0.60): ```bash npx react-native link qclair-quantshield-react-native-android ``` ## 📦 What's Included The package includes: - ✅ Native Android bridge (Kotlin) - ✅ Pre-compiled crypto.jar with ML-KEM + AES-GCM - ✅ All dependencies (Gson, OkHttp, BouncyCastle) - ✅ TypeScript type definitions - ✅ Auto HTTP interception ## 🔄 Version History See [CHANGELOG.md](./CHANGELOG.md) for version history. ## 📄 License MIT License - see [LICENSE](./LICENSE) file for details. ## 🤝 Support For issues and questions: - GitHub Issues: [Report a bug](https://github.com/qclairvoyance12/QuantShield-Client-SDK/issues) - Documentation: [Quick Reference](./QUICK-REFERENCE.md) ## 🚧 Platform Support | Platform | Support | |----------|---------| | Android | ✅ Supported (API 21+) | | iOS | ⏳ Coming soon | | Web | Use [qclair-quantshield-js](https://www.npmjs.com/package/qclair-quantshield-js) | --- **Made with ❤️ for secure mobile communications**