Building an End-to-End Encrypted Chat App with MERN: Public-Key Cryptography and Secure Messaging
Modern messaging applications handle some of the most sensitive information users share: personal conversations, private documents, photos, and other confidential data.
Traditional chat applications commonly encrypt network traffic using HTTPS. This protects information while it travels between a user's device and the server. However, if the server stores messages in plaintext, anyone with sufficient access to the application or database may be able to read them.
End-to-end encryption (E2EE) addresses this problem by ensuring that message content is encrypted on the sender's device and decrypted only on the intended recipient's device.
The backend transports and stores encrypted messages without needing access to their plaintext content.
In this guide, we'll explore how to implement an educational E2EE messaging architecture using:
- React for the frontend.
- Node.js and Express for the backend.
- MongoDB and Mongoose for data storage.
- Socket.IO for real-time communication.
- Web Crypto API for browser-based cryptographic operations.
- RSA-OAEP for encrypting and transporting message encryption keys.
- AES-GCM for encrypting message content.
We'll also discuss private-key protection, key verification, multi-device support, and the security limitations that developers must understand before deploying an encrypted messaging system.
Security note: The implementation in this article demonstrates hybrid encryption using RSA-OAEP and AES-GCM. It is not a complete Signal Protocol implementation. It does not independently provide forward secrecy, post-compromise security, or a complete secure key-exchange protocol. Production messaging applications with strong security requirements should use a reviewed protocol implementation rather than designing their own cryptographic protocol.
1. What Is End-to-End Encryption?
End-to-end encryption is a communication security model in which message content is encrypted before it leaves the sender's device and decrypted only by an authorized recipient.
Consider a conversation between Alice and Bob.
Without E2EE:
- Alice sends a message to the backend.
- The backend receives the plaintext message.
- MongoDB stores the message.
- Bob receives the plaintext message.
HTTPS protects the network connection, but the backend can still access the message.
With E2EE:
- Alice's device encrypts the message.
- The encrypted message is sent to the backend.
- MongoDB stores the ciphertext.
- Bob's device receives the ciphertext.
- Bob's device decrypts the message locally.
The backend only handles encrypted content.
Traditional encryption vs E2EE
| Feature | HTTPS only | End-to-end encryption |
|---|---|---|
| Protects data in transit | Yes | Yes, when used with HTTPS |
| Backend can read message content | Usually yes | No, if correctly implemented |
| Database stores plaintext | Potentially | Ciphertext |
| Decryption happens | At the server/application | On authorized devices |
| Server-side message search | Possible | Requires special client-side approaches |
| Server-side message moderation | Possible | Limited without exposing plaintext |
HTTPS and E2EE solve different problems. A secure messaging application should use both.
2. Understanding the Cryptographic Building Blocks
Before implementing E2EE, understand the difference between symmetric and asymmetric encryption.
Symmetric encryption
Symmetric encryption uses the same secret key to encrypt and decrypt information.
For example:
- Alice generates a secret key.
- Alice encrypts a message using that key.
- Bob receives the encrypted message and the same secret key through a secure mechanism.
- Bob decrypts the message using the key.
AES is a widely used symmetric encryption algorithm.
For our implementation, we'll use AES-256-GCM.
AES-GCM provides authenticated encryption. In addition to encrypting content, it detects unauthorized modifications to the ciphertext.
Asymmetric encryption
Asymmetric encryption uses a key pair:
- Public key: Can be shared with other users.
- Private key: Must remain secret.
In an RSA-OAEP encryption workflow:
- Bob generates an RSA key pair.
- Bob publishes his public key.
- Alice obtains Bob's public key.
- Alice uses that public key to encrypt a small secret.
- Bob decrypts the encrypted secret using his private key.
RSA-OAEP is not suitable for encrypting arbitrarily large chat messages directly. This is why messaging applications commonly use hybrid encryption.
Hybrid encryption
Hybrid encryption combines symmetric and asymmetric cryptography.
Our architecture works like this:
- Alice generates a random AES-256 key for a message.
- Alice encrypts the message using AES-256-GCM.
- Alice encrypts the AES key using Bob's RSA public key.
- Alice sends the ciphertext and encrypted AES key to the backend.
- Bob receives both encrypted values.
- Bob decrypts the AES key using his RSA private key.
- Bob decrypts the message using the recovered AES key.
The backend never receives the plaintext message or the unencrypted AES key.
3. Application Architecture
Let's define the architecture before writing code.
Technology stack
| Layer | Technology |
|---|---|
| Frontend | React |
| Backend | Node.js + Express |
| Database | MongoDB + Mongoose |
| Real-time communication | Socket.IO |
| Encryption | Web Crypto API |
| Authentication | JWT |
| Password hashing | Argon2id or another maintained password-hashing implementation |
| Transport security | HTTPS / WSS |
High-level architecture
ALICE'S DEVICE
┌─────────────────────┐
│ React App │
│ │
│ Plaintext Message │
│ │ │
│ ▼ │
│ AES-256-GCM │
│ │ │
│ ▼ │
│ Ciphertext │
│ + │
│ Wrapped AES Key │
└──────────┬──────────┘
│
│ HTTPS / WSS
▼
NODE.JS BACKEND
┌─────────────────────┐
│ Express API │
│ Socket.IO │
│ │
│ Encrypted Payload │
│ │ │
│ ▼ │
│ MongoDB │
└──────────┬──────────┘
│
│ HTTPS / WSS
▼
BOB'S DEVICE
┌─────────────────────┐
│ React App │
│ │
│ Encrypted Payload │
│ │ │
│ ▼ │
│ RSA-OAEP │
│ Unwrap AES Key │
│ │ │
│ ▼ │
│ AES-256-GCM │
│ │ │
│ ▼ │
│ Plaintext Message │
└─────────────────────┘
The backend is responsible for authentication, authorization, message delivery, persistence, and public-key distribution. Encryption and decryption happen in the clients.
4. Understanding the Key Lifecycle
Key management is one of the most important parts of an E2EE implementation.
A messaging application must manage more than just encryption and decryption.
It needs to handle:
- Initial key generation.
- Public-key distribution.
- Private-key protection.
- Key verification.
- Key replacement.
- Device changes.
- Lost private keys.
- Compromised devices.
For this educational architecture, each user has an RSA key pair.
Key generation
Generate a 3072-bit RSA-OAEP key pair using the browser's Web Crypto API.
export async function generateIdentityKeyPair() {
return crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 3072,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
}
This produces:
- A public key for encrypting AES keys.
- A private key for decrypting AES keys.
The private key must never be uploaded to the backend in plaintext.
Exporting public and private keys
Public keys can be exported in SubjectPublicKeyInfo (SPKI) format.
Private keys can be exported in PKCS#8 format so that the application can protect them before persistent storage.
export async function exportPublicKey(publicKey) {
const exported = await crypto.subtle.exportKey(
"spki",
publicKey
);
return arrayBufferToBase64(exported);
}
export async function exportPrivateKey(privateKey) {
const exported = await crypto.subtle.exportKey(
"pkcs8",
privateKey
);
return arrayBufferToBase64(exported);
}
We'll use a Base64 conversion helper:
export function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
export function base64ToArrayBuffer(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
For large binary payloads, use a streaming or chunked encoding strategy rather than building one large binary string.
5. Protecting the Private Key
Storing a private key in plaintext in localStorage or IndexedDB defeats an important part of the security model.
Instead, encrypt the exported private key using a key derived from a separate encryption passphrase.
The flow:
- Generate the RSA key pair.
- Export the private key.
- Generate a random salt.
- Derive an AES key from the user's encryption passphrase using PBKDF2.
- Encrypt the private key using AES-GCM.
- Store the encrypted private key, salt, and IV in IndexedDB.
- Import the decrypted private key into memory when the user unlocks the application.
The encryption passphrase should not simply be the account password. Account authentication and local private-key protection serve different purposes.
Derive a private-key protection key
export async function deriveStorageKey(passphrase, salt) {
const encoder = new TextEncoder();
const passwordMaterial = await crypto.subtle.importKey(
"raw",
encoder.encode(passphrase),
"PBKDF2",
false,
["deriveKey"]
);
return crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 600000,
hash: "SHA-256",
},
passwordMaterial,
{
name: "AES-GCM",
length: 256,
},
false,
["encrypt", "decrypt"]
);
}
The iteration count is an example starting point, not a universal performance recommendation. Benchmark it on supported devices and select an appropriate value for your threat model.
Encrypt the private key
export async function protectPrivateKey(
privateKey,
passphrase
) {
const exported = await crypto.subtle.exportKey(
"pkcs8",
privateKey
);
const salt = crypto.getRandomValues(
new Uint8Array(16)
);
const iv = crypto.getRandomValues(
new Uint8Array(12)
);
const storageKey = await deriveStorageKey(
passphrase,
salt
);
const encrypted = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
},
storageKey,
exported
);
return {
version: 1,
algorithm: "PBKDF2-SHA256/AES-256-GCM",
salt: arrayBufferToBase64(salt),
iv: arrayBufferToBase64(iv),
ciphertext: arrayBufferToBase64(encrypted),
};
}
The result can be stored in IndexedDB.
Restore the private key
export async function unlockPrivateKey(
encryptedData,
passphrase
) {
const salt = new Uint8Array(
base64ToArrayBuffer(encryptedData.salt)
);
const iv = new Uint8Array(
base64ToArrayBuffer(encryptedData.iv)
);
const ciphertext = base64ToArrayBuffer(
encryptedData.ciphertext
);
const storageKey = await deriveStorageKey(
passphrase,
salt
);
const decrypted = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv,
},
storageKey,
ciphertext
);
return crypto.subtle.importKey(
"pkcs8",
decrypted,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
false,
["decrypt"]
);
}
If the passphrase is incorrect or the encrypted data has been modified, AES-GCM decryption fails.
Important: This protects the private key at rest. It does not protect against malicious JavaScript running in the application origin, browser extensions with sufficient permissions, or a compromised device. An attacker who can execute code in the application may be able to access an unlocked key.
6. Public-Key Registration with Express and MongoDB
The backend needs to maintain users' public keys so that other users can encrypt messages for them.
It must never accept or store users' private keys.
User model
import mongoose from "mongoose";
const publicKeySchema = new mongoose.Schema(
{
keyId: {
type: String,
required: true,
},
algorithm: {
type: String,
default: "RSA-OAEP-3072-SHA256",
},
publicKey: {
type: String,
required: true,
},
fingerprint: {
type: String,
required: true,
},
status: {
type: String,
enum: ["active", "revoked"],
default: "active",
},
createdAt: {
type: Date,
default: Date.now,
},
},
{
_id: false,
}
);
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
publicKeys: [publicKeySchema],
});
export default mongoose.model("User", userSchema);
The keyId identifies a particular key version. The fingerprint helps users compare key identities through a separate verification mechanism.
Public-key registration route
import express from "express";
import User from "../models/User.js";
import authMiddleware from "../middleware/auth.js";
const router = express.Router();
router.post(
"/public-key",
authMiddleware,
async (req, res) => {
try {
const {
keyId,
publicKey,
fingerprint,
} = req.body;
if (!keyId || !publicKey || !fingerprint) {
return res.status(400).json({
message: "Missing key information",
});
}
const user = await User.findById(
req.user.id
);
if (!user) {
return res.status(404).json({
message: "User not found",
});
}
const existingKey = user.publicKeys.find(
(key) => key.keyId === keyId
);
if (existingKey) {
return res.status(409).json({
message: "Key ID already exists",
});
}
user.publicKeys.push({
keyId,
publicKey,
fingerprint,
algorithm: "RSA-OAEP-3072-SHA256",
});
await user.save();
return res.status(201).json({
message: "Public key registered",
});
} catch (error) {
return res.status(500).json({
message: "Unable to register public key",
});
}
}
);
export default router;
This is a simplified route. A production implementation must validate the imported public key, enforce key-size and algorithm policies, compute fingerprints on the server, limit active keys, and protect key changes with appropriate authorization.
Fetching another user's public key
router.get(
"/:userId/public-key",
authMiddleware,
async (req, res) => {
try {
const user = await User.findById(
req.params.userId
).select("publicKeys");
if (!user) {
return res.status(404).json({
message: "User not found",
});
}
const activeKey = user.publicKeys.find(
(key) => key.status === "active"
);
if (!activeKey) {
return res.status(404).json({
message: "No active public key",
});
}
return res.json({
keyId: activeKey.keyId,
publicKey: activeKey.publicKey,
fingerprint: activeKey.fingerprint,
algorithm: activeKey.algorithm,
});
} catch (error) {
return res.status(500).json({
message: "Unable to retrieve public key",
});
}
}
);
In a multi-device application, do not assume one public key per user. Each device should have its own identity and encryption keys. The API should return the verified key bundle for the intended recipient device or devices.
7. Encrypting Messages in React
Now we'll implement the core encryption workflow.
We'll use:
- AES-256-GCM for message encryption.
- RSA-OAEP for encrypting the AES key.
- A fresh AES key and random IV for every message.
- Additional authenticated data (AAD) to bind the ciphertext to its message context.
Import a recipient's public key
export async function importPublicKey(base64Key) {
return crypto.subtle.importKey(
"spki",
base64ToArrayBuffer(base64Key),
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["encrypt", "wrapKey"]
);
}
Encrypt a message
export async function encryptMessage({
plaintext,
recipientPublicKey,
messageId,
conversationId,
senderId,
recipientId,
}) {
const aesKey = await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"]
);
const iv = crypto.getRandomValues(
new Uint8Array(12)
);
const additionalData = new TextEncoder().encode(
JSON.stringify({
messageId,
conversationId,
senderId,
recipientId,
})
);
const ciphertext = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv,
additionalData,
tagLength: 128,
},
aesKey,
new TextEncoder().encode(plaintext)
);
const wrappedKey = await crypto.subtle.wrapKey(
"raw",
aesKey,
recipientPublicKey,
{
name: "RSA-OAEP",
}
);
return {
version: 1,
algorithm: "AES-256-GCM",
keyAlgorithm: "RSA-OAEP-3072-SHA256",
iv: arrayBufferToBase64(iv),
ciphertext: arrayBufferToBase64(ciphertext),
wrappedKey: arrayBufferToBase64(wrappedKey),
aad: {
messageId,
conversationId,
senderId,
recipientId,
},
};
}
The additionalData is authenticated but not encrypted. It binds the encrypted content to the expected message context. The same values must be supplied during decryption.
Notice that the AES key is generated independently for each message. This avoids reusing one long-lived AES key for every message in a conversation.
Why use a new IV for every message?
AES-GCM requires IV uniqueness for a given key.
A 96-bit random IV is commonly used with AES-GCM. Because we generate a fresh AES key for every message, each key is used for one message encryption in this example.
Never reuse an AES-GCM IV with the same key.
8. Decrypting Messages on the Recipient's Device
The recipient uses their private key to unwrap the AES key, then decrypts the message.
Decryption implementation
export async function decryptMessage({
encryptedMessage,
recipientPrivateKey,
}) {
const {
wrappedKey,
iv,
ciphertext,
aad,
} = encryptedMessage;
const aesKey = await crypto.subtle.unwrapKey(
"raw",
base64ToArrayBuffer(wrappedKey),
recipientPrivateKey,
{
name: "RSA-OAEP",
},
{
name: "AES-GCM",
length: 256,
},
false,
["decrypt"]
);
const additionalData = new TextEncoder().encode(
JSON.stringify(aad)
);
const decrypted = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: new Uint8Array(
base64ToArrayBuffer(iv)
),
additionalData,
tagLength: 128,
},
aesKey,
base64ToArrayBuffer(ciphertext)
);
return new TextDecoder().decode(decrypted);
}
If the ciphertext, IV, authentication tag, or associated data has been modified, authenticated decryption fails.
The application should treat this as a decryption failure rather than displaying potentially corrupted content.
9. Storing Encrypted Messages in MongoDB
The backend should never need to understand the plaintext message.
Instead, store the encrypted payload and the information required for message delivery.
Message model
import mongoose from "mongoose";
const messageSchema = new mongoose.Schema(
{
conversationId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
index: true,
},
senderId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
index: true,
},
recipientId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
index: true,
},
messageId: {
type: String,
required: true,
unique: true,
},
encryptedPayload: {
version: {
type: Number,
required: true,
},
algorithm: {
type: String,
required: true,
},
keyAlgorithm: {
type: String,
required: true,
},
iv: {
type: String,
required: true,
},
ciphertext: {
type: String,
required: true,
},
wrappedKey: {
type: String,
required: true,
},
aad: {
messageId: String,
conversationId: String,
senderId: String,
recipientId: String,
},
},
createdAt: {
type: Date,
default: Date.now,
},
}
);
messageSchema.index({
conversationId: 1,
createdAt: -1,
});
export default mongoose.model(
"Message",
messageSchema
);
The schema is designed for a one-recipient-device example. For real multi-device messaging, replace the single wrappedKey with a collection of recipient-device key envelopes.
For example:
encryptedPayload: {
ciphertext: "...",
iv: "...",
keyEnvelopes: [
{
deviceId: "device-a",
keyId: "key-a",
wrappedKey: "..."
},
{
deviceId: "device-b",
keyId: "key-b",
wrappedKey: "..."
}
]
}
This allows one ciphertext to be encrypted once while its AES key is separately wrapped for each authorized recipient device.
Backend message route
router.post(
"/",
authMiddleware,
async (req, res) => {
try {
const {
conversationId,
recipientId,
messageId,
encryptedPayload,
} = req.body;
if (
!conversationId ||
!recipientId ||
!messageId ||
!encryptedPayload
) {
return res.status(400).json({
message: "Invalid message payload",
});
}
// Verify that the authenticated sender
// belongs to this conversation.
// Also verify recipient membership.
const message = await Message.create({
conversationId,
senderId: req.user.id,
recipientId,
messageId,
encryptedPayload,
});
return res.status(201).json({
message: "Encrypted message stored",
id: message._id,
});
} catch (error) {
return res.status(500).json({
message: "Unable to store message",
});
}
}
);
The omitted membership check is essential: never trust a client-supplied conversation ID or recipient ID without checking authorization on the server.
Also validate payload sizes, allowed algorithms, field types, and message identifiers before saving data.
10. Real-Time Encrypted Messaging with Socket.IO
Socket.IO can deliver encrypted messages without knowing their plaintext content.
The client encrypts the message before emitting an event. The server forwards the encrypted payload to the recipient.
Client-side sending
socket.emit("send-message", {
conversationId,
recipientId,
messageId,
encryptedPayload,
});
Server-side handling
io.on("connection", (socket) => {
socket.on("send-message", async (data) => {
try {
const userId = socket.user.id;
// Validate conversation membership.
// Validate recipient access.
// Validate payload size and structure.
const message = await Message.create({
conversationId: data.conversationId,
senderId: userId,
recipientId: data.recipientId,
messageId: data.messageId,
encryptedPayload: data.encryptedPayload,
});
io.to(`user:${data.recipientId}`).emit(
"new-message",
{
id: message._id,
messageId: message.messageId,
conversationId: message.conversationId,
senderId: message.senderId,
encryptedPayload: message.encryptedPayload,
createdAt: message.createdAt,
}
);
} catch (error) {
socket.emit("message-error", {
message: "Unable to send message",
});
}
});
});
The example assumes socket.user is established by authentication middleware and that user rooms are joined securely.
Never trust a client-provided sender ID. Derive the sender identity from the authenticated socket.
For production, also implement:
- Socket authentication and token expiration handling.
- Conversation membership checks.
- Rate limiting.
- Duplicate-message protection.
- Message delivery acknowledgements.
- Offline message persistence.
- Reconnection handling.
- Pagination.
- Payload-size limits.
For more on real-time communication choices, see Socket.IO vs WebSockets vs Server-Sent Events.
11. The Most Important Security Problem: Public-Key Verification
There is a major problem with simply downloading another user's public key from the backend.
What if the backend returns an attacker's public key instead of Bob's?
Alice would encrypt the message using the attacker's public key. The attacker could decrypt it using their private key.
This is a public-key substitution attack.
HTTPS protects the connection to the server, but it does not independently prove that a particular public key genuinely belongs to Bob.
Key fingerprints
A fingerprint is a digest derived from a public key.
For example, a client can calculate a SHA-256 fingerprint of the public key's SPKI representation.
export async function getKeyFingerprint(publicKey) {
const exported = await crypto.subtle.exportKey(
"spki",
publicKey
);
const digest = await crypto.subtle.digest(
"SHA-256",
exported
);
return Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
Users can compare fingerprints through an independent trusted channel, such as:
- Scanning each other's QR codes in person.
- Comparing a safety number during a call.
- Verifying a trusted device identity.
- Using a trusted key-transparency system.
A fingerprint displayed by the same potentially compromised server is not sufficient verification by itself.
12. Confidentiality Is Not the Same as Sender Authentication
One subtle but important point: RSA-OAEP encryption does not prove who sent a message.
Anyone with Bob's public key can encrypt a message for Bob.
Therefore, Bob can decrypt the message, but that alone does not prove that Alice created it.
If sender authentication is required, the application needs an additional mechanism.
One approach is digital signatures.
For example, Alice can sign a canonical message envelope using a separate signing private key. Bob verifies the signature using Alice's trusted public signing key.
The signing key should be distinct from the encryption key.
However, signatures alone do not solve public-key substitution. Bob must first have a trustworthy way to associate Alice's signing key with Alice's identity.
A mature messaging protocol handles authentication, key agreement, and message-key evolution as part of a coordinated design.
13. Why Basic RSA-OAEP E2EE Is Not Enough for Production
The implementation so far provides a useful demonstration of hybrid encryption. However, it has important security limitations.
No forward secrecy
Forward secrecy means that compromising a long-term key should not automatically expose previously recorded conversations.
In our example, the sender encrypts each message's AES key using the recipient's long-term RSA public key.
If an attacker obtains the recipient's private key later and has recorded previous encrypted messages, the attacker may be able to decrypt those historical messages.
A fresh AES key for each message does not solve this problem.
No post-compromise security
Post-compromise security describes the ability of a communication session to recover security after a device or key has been compromised and the protocol successfully advances through new secret material.
Our simple RSA-based design does not provide this capability.
No complete key-exchange protocol
A production messaging protocol must securely establish shared secrets and authenticate identities.
Simply downloading public keys from a server and encrypting AES keys is not a complete authenticated key-exchange protocol.
No automatic multi-device security
If a user logs in on a phone, laptop, and tablet, the application must decide which devices can decrypt each message.
A single user-level key is not a complete device-management architecture.
No secure group messaging
Group conversations introduce additional problems:
- Group membership changes.
- Device additions and removals.
- Key distribution.
- Membership authentication.
- Message ordering.
- Forward secrecy.
- Group key updates.
A production group-messaging system needs a dedicated group key-management protocol.
14. Understanding the Signal Protocol and Double Ratchet
If you're building a serious private messaging application, study the Signal Protocol.
The Double Ratchet algorithm is designed to derive new message keys as conversations progress.
Its core idea is that message keys are not simply reused forever. The protocol advances key material over time.
The Double Ratchet combines:
- Symmetric-key ratchets.
- Diffie-Hellman ratchets.
- Root keys.
- Chain keys.
- Per-message keys.
- Authenticated encryption.
This provides stronger security properties than a static RSA public-key encryption design.
The broader Signal protocol ecosystem also includes authenticated initial key agreement mechanisms.
For group messaging, the Messaging Layer Security (MLS) standard is another important protocol to study.
Do not attempt to implement the Signal Protocol or MLS from scratch by copying a few cryptographic operations. Use a maintained, reviewed implementation appropriate to your application and its supported platforms.
15. Multi-Device E2EE Architecture
A practical messaging product must consider that users rarely have only one device.
Consider this scenario:
- Alice uses a laptop and mobile phone.
- Bob uses a desktop and mobile phone.
- Alice sends a message from her laptop.
Which devices should be able to decrypt the message?
A common architecture uses a separate cryptographic identity for every device.
Example:
Alice
├── Laptop
│ ├── Identity Key
│ └── Device Key
│
└── Mobile
├── Identity Key
└── Device Key
Bob
├── Desktop
│ ├── Identity Key
│ └── Device Key
│
└── Mobile
├── Identity Key
└── Device Key
The sender encrypts the content once and creates an appropriate encrypted key envelope for each authorized recipient device.
The sender's other devices may also need access to sent messages. This requires an explicit sender-device synchronization design.
Do not simply share the same private key across every device without considering device compromise, revocation, backups, and key lifecycle.
16. Handling Key Rotation and Lost Devices
Key management must continue after the initial registration process.
Consider these situations:
User changes devices
A new device should establish its own cryptographic identity.
The application needs a secure process to authorize the new device and, where supported, transfer or restore access to existing conversations.
User loses a device
The lost device's keys should be revoked from the account's trusted-device list.
Revocation should prevent the device from receiving new messages.
It cannot guarantee that an attacker who already obtained the private key will lose access to previously recorded ciphertext.
User forgets the encryption passphrase
If the private key is protected only by a passphrase and there is no recovery mechanism, the user may permanently lose access to historical encrypted messages.
This is an important product decision.
Possible recovery approaches include:
- An encrypted user-controlled backup.
- A recovery key generated during initial setup.
- A separately authorized trusted device.
- A carefully designed recovery mechanism that does not expose plaintext private keys to the backend.
Every recovery mechanism introduces security and usability trade-offs.
User rotates encryption keys
A new key should be registered with a new key identifier.
Old keys may need to remain available to decrypt historical messages.
Key rotation should also trigger a verification or notification process so that other users can detect unexpected identity changes.
17. What Should the Backend Be Able to See?
E2EE protects message content, but it does not automatically hide all information about a conversation.
Depending on the application design, the backend may still see:
| Information | Usually visible to backend? |
|---|---|
| Encrypted message content | No plaintext access |
| Sender ID | Yes |
| Recipient ID | Yes |
| Conversation ID | Yes |
| Message timestamp | Yes |
| Delivery status | Yes |
| Message size | Usually |
| Public keys | Yes |
| Private keys | No, if correctly designed |
| Online status | Usually |
| Group membership | Usually |
This information is known as metadata.
Metadata can reveal communication patterns, relationships, activity times, and other sensitive information.
If metadata privacy is a requirement, the architecture must address it separately.
18. E2EE Security Checklist
Before deploying an encrypted messaging application, review these areas.
Cryptographic implementation
- Use established cryptographic algorithms and maintained implementations.
- Prefer authenticated encryption such as AES-GCM.
- Generate keys using cryptographically secure randomness.
- Never reuse an AES-GCM IV with the same key.
- Never encrypt passwords using reversible encryption.
- Use separate keys for encryption and signing.
- Validate authentication tags and reject failed decryption.
- Include versioning and algorithm identifiers in encrypted payloads.
Key management
- Generate private keys on the client.
- Never upload plaintext private keys.
- Protect private keys at rest.
- Verify public-key fingerprints.
- Support key rotation.
- Handle revoked and lost devices.
- Plan for encrypted backups and recovery.
- Design multi-device key distribution deliberately.
Backend security
- Enforce HTTPS and WSS.
- Authenticate Socket.IO connections.
- Verify conversation membership.
- Validate message payloads.
- Limit message sizes.
- Prevent replay and duplicate processing where required.
- Apply rate limiting.
- Never log plaintext messages or sensitive key material.
- Keep authorization checks independent of client-provided identities.
Frontend security
- Protect the application against XSS.
- Apply a strict Content Security Policy.
- Avoid unsafe HTML rendering.
- Protect authentication sessions.
- Keep private keys out of logs and analytics.
- Avoid third-party scripts on sensitive messaging pages.
- Clear unlocked cryptographic state when appropriate.
- Use a secure local-storage and backup strategy.
Production readiness
- Define a threat model.
- Have the cryptographic design independently reviewed.
- Test key rotation and recovery.
- Test malicious and malformed ciphertext.
- Test device revocation.
- Test concurrent message delivery.
- Establish an incident-response plan.
- Prefer a reviewed protocol such as Signal or MLS where the requirements demand stronger guarantees.
19. Common E2EE Implementation Mistakes
Mistake 1: Encrypting messages only on the backend
If the backend receives plaintext and encrypts it before storing it, the server still has access to the original message.
Encryption must happen on the sender's device.
Mistake 2: Storing private keys in plaintext
A private key stored directly in localStorage or IndexedDB can be exposed if the browser profile or application origin is compromised.
Protect keys at rest and consider the limitations of browser-based key storage.
Mistake 3: Assuming HTTPS means E2EE
HTTPS protects data in transit. It does not prevent the application server from reading plaintext messages.
Mistake 4: Trusting public keys returned by the server
A malicious or compromised server could replace a public key.
Use fingerprints, identity verification, or a suitable authenticated key-distribution mechanism.
Mistake 5: Using one permanent AES key
Long-lived symmetric keys increase the consequences of compromise.
Use a protocol that manages message keys and their lifecycle appropriately.
Mistake 6: Ignoring device changes
A new device cannot automatically decrypt old messages without a deliberate key-transfer or recovery strategy.
Mistake 7: Claiming complete security from encryption alone
Encryption does not automatically protect against XSS, compromised devices, malicious updates, metadata exposure, account takeover, or insecure recovery mechanisms.
Security requires the entire system to be designed carefully.
20. Conclusion
End-to-end encryption changes how a messaging application handles sensitive information.
Instead of trusting the backend with plaintext messages, the application encrypts content on the sender's device and decrypts it on authorized recipient devices.
Using a MERN stack, we can build the surrounding infrastructure with React, Express, MongoDB, and Socket.IO while performing cryptographic operations in the browser through the Web Crypto API.
The most important concepts to understand are:
- Symmetric encryption is efficient for message content.
- Asymmetric cryptography can protect the delivery of encryption keys.
- Authenticated encryption detects unauthorized message modifications.
- Private-key protection is essential.
- Public-key verification prevents key-substitution attacks.
- Forward secrecy and multi-device security require more than basic RSA encryption.
- A production E2EE system should use a reviewed cryptographic protocol.
The key lesson is that E2EE is not just an encryption function added to a chat application. It is an architectural decision that affects identity, authentication, storage, device management, recovery, and the entire messaging lifecycle.
For developers building real-time MERN applications, understanding these principles is a valuable foundation for designing privacy-focused products.



