Short answer: end-to-end encryption (E2EE) means only the two people chatting can read the messages, not even your server. Each device creates a key pair, they exchange public keys, each side computes the same shared secret with ECDH, derives an encryption key from it, and encrypts every message with an authenticated cipher such as AES-GCM. The server only ever sees ciphertext.
This article explains each step in plain language and shows the Kotlin code using only standard Android APIs.
I'm Padmakar Garg, a Senior Android Developer. I work on secure messaging, encrypted calling and Android security. The code below is for understanding how E2EE works. For production, use a vetted protocol and library (see the end).
The big picture
Alice Server Bob
| generate key pair (A_priv, A_pub) | generate key pair (B_priv, B_pub) |
|---- A_pub ---------------------------->|<--------------------------- B_pub ------|
|<--- B_pub -----------------------------|-----------------------------> A_pub ---|
| secret = ECDH(A_priv, B_pub) | secret = ECDH(B_priv, A_pub) |
| (both get the SAME secret) | |
| key = HKDF(secret) | key = HKDF(secret) |
|---- AES-GCM(key, message) ------------>|--------- ciphertext only -------------->|
The magic is that Alice and Bob end up with the same secret without ever sending it. The server relays public keys and ciphertext, and cannot compute the secret.
Step 1: Generate a key pair
Each device creates an elliptic-curve key pair. The private key never leaves the device.
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.spec.ECGenParameterSpec
fun generateKeyPair(): KeyPair {
val generator = KeyPairGenerator.getInstance("EC")
generator.initialize(ECGenParameterSpec("secp256r1"))
return generator.generateKeyPair()
}
To send the public key to the other user, encode it to bytes. To receive one, decode it:
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.X509EncodedKeySpec
fun PublicKey.toBytes(): ByteArray = encoded
fun publicKeyFromBytes(bytes: ByteArray): PublicKey =
KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(bytes))
Step 2: Compute the shared secret with ECDH
Elliptic-curve Diffie-Hellman (ECDH) combines your private key with their public key. The maths guarantees both sides get the same result.
import javax.crypto.KeyAgreement
import java.security.PrivateKey
fun sharedSecret(myPrivate: PrivateKey, theirPublic: PublicKey): ByteArray {
val agreement = KeyAgreement.getInstance("ECDH")
agreement.init(myPrivate)
agreement.doPhase(theirPublic, true)
return agreement.generateSecret()
}
Alice calls sharedSecret(A_priv, B_pub) and Bob calls sharedSecret(B_priv, A_pub). The two byte arrays are identical.
Step 3: Derive a proper encryption key
Never use the raw ECDH output as an AES key. Run it through a key derivation function (KDF) such as HKDF. Here is a small HMAC-SHA256 based version for a 32-byte key:
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
fun hkdfSha256(secret: ByteArray, info: ByteArray): ByteArray {
val mac = Mac.getInstance("HmacSHA256")
// Extract
mac.init(SecretKeySpec(ByteArray(32), "HmacSHA256"))
val prk = mac.doFinal(secret)
// Expand (one block is enough for a 32-byte key)
mac.init(SecretKeySpec(prk, "HmacSHA256"))
mac.update(info)
mac.update(1.toByte())
return mac.doFinal()
}
val key = hkdfSha256(secret, "chat-v1".toByteArray())
The info string binds the key to its purpose, so the same secret can never be reused accidentally for something else.
Step 4: Encrypt with AES-GCM
AES-GCM gives you confidentiality and integrity in one operation. If anyone modifies the ciphertext, decryption fails.
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
fun encrypt(key: ByteArray, plaintext: ByteArray, aad: ByteArray = ByteArray(0)): ByteArray {
val iv = ByteArray(12).also { SecureRandom().nextBytes(it) }
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv))
cipher.updateAAD(aad)
return iv + cipher.doFinal(plaintext) // prepend the IV
}
fun decrypt(key: ByteArray, payload: ByteArray, aad: ByteArray = ByteArray(0)): ByteArray {
val iv = payload.copyOfRange(0, 12)
val ciphertext = payload.copyOfRange(12, payload.size)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv))
cipher.updateAAD(aad)
return cipher.doFinal(ciphertext)
}
Use the chat ID and message ID as the aad (additional authenticated data). That way a ciphertext cannot be moved to another conversation without detection.
The mistakes that quietly break E2EE
1. Reusing an IV with the same key
In GCM, one repeated IV with the same key can leak plaintext relationships and break authentication. Use a fresh random 12-byte IV for each message, or a strict counter, and rotate keys regularly.
2. Trusting the server for public keys
If the server hands you the wrong public key, it can sit in the middle and read everything (a man-in-the-middle attack). Let users compare a fingerprint (for example a hash of both public keys) out of band:
fun fingerprint(a: PublicKey, b: PublicKey): String {
val parts = listOf(a.encoded, b.encoded).sortedBy { it.contentHashCode() }
val digest = java.security.MessageDigest.getInstance("SHA-256")
parts.forEach { digest.update(it) }
return digest.digest().joinToString("") { "%02x".format(it) }.take(32)
}
Show it as a "safety number" that two people can compare in person or on a call.
3. No forward secrecy
If one long-term key leaks, an attacker could decrypt all past messages. Use ephemeral keys per session and rotate them as messages flow. The Signal protocol does this with the Double Ratchet algorithm.
4. Storing private keys carelessly
Never keep private keys in SharedPreferences or a plain file. Use the Android Keystore where supported. ECDH operations inside the Keystore need a recent Android version, so check the documentation for the API level you support.
5. Believing the metadata is hidden
E2EE protects message content. The server can still see who talks to whom, when and how often, unless you design for that separately.
What to use in production
Writing your own protocol is risky, because tiny mistakes are invisible and fatal. For a real app, prefer:
- the Signal protocol libraries,
- Google Tink for safe cryptographic primitives,
- libsodium for modern, hard-to-misuse APIs.
Use the code in this article to understand what those libraries do, not to replace them. If you want to see a protocol implemented from a specification, I've published a Kotlin SDK implementing the MTProto 2.0 primitives (AES-IGE and Diffie-Hellman key exchange) here: github.com/gargpadmakar/MTProtoCrypto.
Summary
- Each device makes a key pair, and only public keys are exchanged.
- ECDH gives both sides the same shared secret without sending it.
- Run the secret through a KDF to get the real AES key.
- Encrypt each message with AES-GCM, a fresh IV and the chat context as AAD.
- Defend against man-in-the-middle with fingerprints, and aim for forward secrecy.
- In production, use Signal protocol, Tink or libsodium instead of rolling your own.
About the author: Padmakar Garg is a Senior Android Developer with 8+ years of experience in Kotlin, Jetpack Compose and mobile security, building real-time encrypted messaging apps. Portfolio and blog: gargpadmakar.github.io. Connect on LinkedIn.
Top comments (2)
The AAD detail is the one I'd steal — binding the ciphertext to the chat ID and message ID so a message can't be replayed into another conversation is the kind of thing that's easy to skip and expensive to learn later. Same with the safety-number fingerprint: most E2EE explainers stop at 'the server can't read it' and never mention the server handing you the wrong public key.
The part I'm still wrestling with, from building offline-first on Android: the private key lives in the Keystore and never leaves the device — which is exactly right — but if the user loses the phone, that identity is gone with it. How would you handle key backup or recovery without reintroducing a server that can see the key? Is there a version of this where a user can move to a new phone without trusting anyone with the private key?
That's a very important trade-off in E2EE design. I would approach this using client-side encrypted key backup rather than allowing the server to store the raw private key.
My preferred approach would be:
I'd also consider QR-based device-to-device transfer as an alternative, allowing users to migrate their identity directly without involving the server.
One important detail: Android Keystore keys are generally non-exportable, so I'd design a separate backup mechanism rather than trying to extract the original Keystore key.
The fundamental principle is that recovery should not require trusting the server with your private key. If the user loses both their device and recovery secret, permanent identity loss may be an intentional security trade-off.
That's the balance I'd aim for: user-controlled recovery without compromising the zero-knowledge nature of E2EE.