Make an easy and simple e2e encryption system in Typescript utilizing native JS, for a…
- User
Make an easy and simple e2e encryption system in Typescript utilizing native JS, for a chat app, allowing encryption and decryption of messages and files
- Assistant
Creating a simple end-to-end (E2E) encryption system for a chat application using TypeScript and native JavaScript involves several steps. We'll leverage the Web Crypto API, which is a native JavaScript API for performing cryptographic operations.
This guide will cover:
- Key Generation and Management
- Encrypting Messages and Files
- Decrypting Messages and Files
- Putting It All Together
Let's dive in!
1. Key Generation and Management
For E2E encryption, it's essential to ensure that only the communicating parties can encrypt and decrypt the messages. We'll use symmetric encryption (AES-GCM) for simplicity, where both parties share the same secret key.
Generating a Symmetric Key
// cryptoService.ts export class CryptoService { private key: CryptoKey | null = null; // Generates a new AES-GCM symmetric key async generateKey(): Promise<void> { this.key = await window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, // extractable ["encrypt", "decrypt"] ); } // Exports the key to a base64 string for storage or transmission async exportKey(): Promise<string | null> { if (!this.key) return null; const raw = await window.crypto.subtle.exportKey("raw", this.key); return this.arrayBufferToBase64(raw); } // Imports a base64 string to a CryptoKey async importKey(base64Key: string): Promise<void> { const raw = this.base64ToArrayBuffer(base64Key); this.key = await window.crypto.subtle.importKey( "raw", raw, "AES-GCM", true, ["encrypt", "decrypt"] ); } // Utility functions private arrayBufferToBase64(buffer: ArrayBuffer): string { const bytes = new Uint8Array(buffer); let binary = ""; bytes.forEach((b) => (binary += String.fromCharCode(b))); return window.btoa(binary); } private base64ToArrayBuffer(base64: string): ArrayBuffer { const binary = window.atob(base64); const bytes = new Uint8Array(binary.length); Array.from(binary).forEach((char, i) => { bytes[i] = char.charCodeAt(0); }); return bytes.buffer; } getKey(): CryptoKey | null { return this.key; } }Explanation:
- generateKey: Creates a new AES-GCM symmetric key.
- exportKey: Exports the key to a base64 string, which can be stored or shared securely.
- importKey: Imports a base64-encoded key string back into a
CryptoKeyobject. - Utility Functions: Convert between ArrayBuffers and base64 strings.
2. Encrypting Messages and Files
We'll create functions to encrypt both text messages and binary files. For AES-GCM, it's crucial to use a unique initialization vector (IV) for each encryption operation.
Encrypting Data
// cryptoService.ts (continued) export class CryptoService { // ... previous code ... // Encrypts plaintext (string) and returns IV and ciphertext in base64 async encryptMessage(plaintext: string): Promise<{ iv: string; ciphertext: string } | null> { if (!this.key) throw new Error("Key not set"); const encoder = new TextEncoder(); const data = encoder.encode(plaintext); const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV for AES-GCM const ciphertext = await window.crypto.subtle.encrypt( { name: "AES-GCM", iv: iv, }, this.key, data ); return { iv: this.arrayBufferToBase64(iv.buffer), ciphertext: this.arrayBufferToBase64(ciphertext), }; } // Encrypts a file (ArrayBuffer) and returns IV and ciphertext in base64 async encryptFile(fileData: ArrayBuffer): Promise<{ iv: string; ciphertext: string } | null> { if (!this.key) throw new Error("Key not set"); const iv = window.crypto.getRandomValues(new Uint8Array(12)); const ciphertext = await window.crypto.subtle.encrypt( { name: "AES-GCM", iv: iv, }, this.key, fileData ); return { iv: this.arrayBufferToBase64(iv.buffer), ciphertext: this.arrayBufferToBase64(ciphertext), }; } // ... utility functions ... }Explanation:
- encryptMessage: Takes a plaintext string, encodes it, generates a random IV, encrypts the data, and returns both IV and ciphertext as base64 strings.
- encryptFile: Similar to
encryptMessagebut works with binary data (ArrayBuffer).
3. Decrypting Messages and Files
Correspondingly, we need functions to decrypt the encrypted data using the shared key and the IV used during encryption.
Decrypting Data
// cryptoService.ts (continued) export class CryptoService { // ... previous code ... // Decrypts ciphertext and returns plaintext string async decryptMessage(ivBase64: string, ciphertextBase64: string): Promise<string | null> { if (!this.key) throw new Error("Key not set"); const iv = new Uint8Array(this.base64ToArrayBuffer(ivBase64)); const ciphertext = this.base64ToArrayBuffer(ciphertextBase64); const decrypted = await window.crypto.subtle.decrypt( { name: "AES-GCM", iv: iv, }, this.key, ciphertext ); const decoder = new TextDecoder(); return decoder.decode(decrypted); } // Decrypts ciphertext and returns file data as ArrayBuffer async decryptFile(ivBase64: string, ciphertextBase64: string): Promise<ArrayBuffer | null> { if (!this.key) throw new Error("Key not set"); const iv = new Uint8Array(this.base64ToArrayBuffer(ivBase64)); const ciphertext = this.base64ToArrayBuffer(ciphertextBase64); const decrypted = await window.crypto.subtle.decrypt( { name: "AES-GCM", iv: iv, }, this.key, ciphertext ); return decrypted; } // ... utility functions ... }Explanation:
- decryptMessage: Takes the base64-encoded IV and ciphertext, decodes them, decrypts the data, and returns the plaintext string.
- decryptFile: Decrypts binary data and returns the original
ArrayBuffer.
4. Putting It All Together
Here's how you can use the
CryptoServicein your chat application to encrypt and decrypt messages and files.Example Usage
// main.ts import { CryptoService } from "./cryptoService"; async function main() { const cryptoService = new CryptoService(); // Generate a new key (in a real app, you would share this key securely between users) await cryptoService.generateKey(); // Export the key to share with the other user const exportedKey = await cryptoService.exportKey(); console.log("Exported Key:", exportedKey); // Simulate importing the key on the receiving side const cryptoServiceReceiver = new CryptoService(); if (exportedKey) { await cryptoServiceReceiver.importKey(exportedKey); } // Encrypt a message const message = "Hello, this is a secret message!"; const encryptedMessage = await cryptoService.encryptMessage(message); console.log("Encrypted Message:", encryptedMessage); // Decrypt the message if (encryptedMessage) { const decryptedMessage = await cryptoServiceReceiver.decryptMessage( encryptedMessage.iv, encryptedMessage.ciphertext ); console.log("Decrypted Message:", decryptedMessage); } // Encrypt a file (for example, a simple text file) const fileContent = "This is the content of the file."; const encoder = new TextEncoder(); const fileData = encoder.encode(fileContent).buffer; const encryptedFile = await cryptoService.encryptFile(fileData); console.log("Encrypted File:", encryptedFile); // Decrypt the file if (encryptedFile) { const decryptedFileBuffer = await cryptoServiceReceiver.decryptFile( encryptedFile.iv, encryptedFile.ciphertext ); const decoder = new TextDecoder(); const decryptedFileContent = decoder.decode(decryptedFileBuffer!); console.log("Decrypted File Content:", decryptedFileContent); } } main().catch((err) => console.error(err));Explanation:
-
Key Generation and Sharing:
- The
cryptoServicegenerates a new symmetric key. - The key is exported as a base64 string (
exportedKey), which should be securely shared with the other user (e.g., via a secure key exchange mechanism). - The
cryptoServiceReceiverimports the shared key.
- The
-
Encrypting and Decrypting a Message:
- The sender encrypts a plaintext message.
- The receiver decrypts the ciphertext using the shared key.
-
Encrypting and Decrypting a File:
- The sender encrypts file data (simulated here with a simple string).
- The receiver decrypts the ciphertext back to the original file content.
Security Considerations
While the above implementation provides a basic E2E encryption system, real-world applications require more robust security measures:
- Key Exchange: Securely exchanging keys between users is critical. Consider using asymmetric encryption (e.g., ECDH) to exchange symmetric keys securely.
- Authentication: Ensure that the keys are associated with the correct users to prevent man-in-the-middle attacks.
- Key Management: Implement proper key storage and rotation strategies.
- Error Handling: Enhance error handling to cover different failure scenarios.
- Integrity and Authentication: AES-GCM provides built-in integrity checks, but always validate decrypted data.
Additional Enhancements
To further enhance the encryption system, consider the following:
- Asymmetric Encryption: Use RSA or ECC for key exchanges, allowing you to establish a secure symmetric key between users without prior key sharing.
- Message Authentication Codes (MAC): Although AES-GCM includes authentication, additional MACs can provide extra security layers.
- Hybrid Encryption: Combine symmetric and asymmetric encryption for efficient and secure communication.
- File Chunking: For large files, implement chunked encryption and decryption to handle data more efficiently.
Conclusion
This guide provided a straightforward approach to implementing an end-to-end encryption system in TypeScript using native JavaScript's Web Crypto API. By following the steps outlined above, you can encrypt and decrypt messages and files securely within your chat application. Remember to consider additional security measures for a production-ready system.
Feel free to expand upon this foundation to build a more comprehensive and secure encryption system tailored to your application's needs.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.