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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating an end-to-end (E2E) encryption system in TypeScript using native JavaScript is a great way to ensure secure communication in your chat app. Below, I'll guide you through building a simple E2E encryption system that allows users to encrypt and decrypt messages and files using the Web Crypto API, which is built into modern browsers.
Overview
We will:
Generate key pairs for each user using Elliptic Curve Diffie-Hellman (ECDH).
Exchange public keys between users.
Derive a shared secret key from the key pairs.
Encrypt and decrypt messages and files using the shared secret key with AES-GCM.
Step 1: Generate Key Pairs
Each user needs to generate a public/private key pair.
Here's how you might use these functions in your chat app:
typescript
// User A generates their key pair
const userAKeyPair = await generateKeyPair();
const userAPublicKeyRaw = await exportPublicKey(userAKeyPair.publicKey);
// User B generates their key pair
const userBKeyPair = await generateKeyPair();
const userBPublicKeyRaw = await exportPublicKey(userBKeyPair.publicKey);
// Exchange public keys between User A and User B
// This would typically be done via your server or signaling mechanism
// User A imports User B's public key
const userBPublicKey = await importPublicKey(userBPublicKeyRaw);
// User B imports User A's public key
const userAPublicKey = await importPublicKey(userAPublicKeyRaw);
// Both users derive the shared secret key
const userASharedKey = await deriveSharedKey(
userAKeyPair.privateKey,
userBPublicKey
);
const userBSharedKey = await deriveSharedKey(
userBKeyPair.privateKey,
userAPublicKey
);
// User A encrypts a message
const message = "Hello, User B!";
const encrypted = await encryptMessage(userASharedKey, message);
// User B decrypts the message
const decryptedMessage = await decryptMessage(
userBSharedKey,
encrypted.iv,
encrypted.ciphertext
);
console.log(decryptedMessage); // "Hello, User B!"
Handling Files
To encrypt and decrypt files (blobs), you can modify the encryption and decryption functions slightly.
Encrypting Files
typescript
async function encryptFile(
sharedKey: CryptoKey,
file: ArrayBuffer
): Promise<{ iv: ArrayBuffer; ciphertext: ArrayBuffer }> {
// Generate a random initialization vector
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
},
sharedKey,
file
);
return {
iv: iv.buffer,
ciphertext: ciphertext,
};
}
// Assume you have a file input element
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
fileInput.addEventListener("change", async () => {
if (fileInput.files && fileInput.files[0]) {
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
// Encrypt the file
const encryptedFile = await encryptFile(userASharedKey, arrayBuffer);
// Send encryptedFile.ciphertext and encryptedFile.iv to User B
// User B decrypts the file
const decryptedFileBuffer = await decryptFile(
userBSharedKey,
encryptedFile.iv,
encryptedFile.ciphertext
);
// Create a Blob from the decrypted data
const decryptedBlob = new Blob([decryptedFileBuffer], { type: file.type });
// Download or display the decrypted file
const url = URL.createObjectURL(decryptedBlob);
const link = document.createElement("a");
link.href = url;
link.download = file.name;
link.click();
}
});
Important Considerations
Security Practices: Cryptography is complex. Ensure you handle keys and data securely. Avoid logging sensitive information. Use secure channels for key exchange.
Authentication: The above example does not include authentication. It's crucial to verify the identity of the users to prevent man-in-the-middle attacks. Consider implementing digital signatures using ECDSA.
Key Management: In a real-world application, you'll need to manage keys across sessions. Consider using a key management system or incorporating protocols like Signal for robust security.
Error Handling: Make sure to include comprehensive error handling in your production code.
Browser Support: The Web Crypto API is widely supported in modern browsers, but ensure compatibility if you need to support older browsers.
Conclusion
By using the Web Crypto API, we created a simple E2E encryption system without relying on external libraries. This system allows users to securely exchange messages and files in your chat app.
Always keep in mind the security implications and best practices when implementing cryptographic functions. If your application requires strong security guarantees, consider using established cryptographic libraries and consult with a security expert.
If you have any questions or need further clarification on any part of this implementation, feel free to ask!