In this lesson, you will learn how to implement the Elliptic Curve Diffie-Hellman (ECDH) protocol to establish an ephemeral session key between two resource-constrained IoT devices.
The Challenge of Key Distribution
In insecure wireless networks—like those using BLE or LoRaWAN—we cannot simply transmit a symmetric key over the air. If an attacker intercepts it, all future communication is compromised. While symmetric cryptography (Lesson 14) is fast, it relies on having a pre-shared secret. Asymmetric cryptography (Lesson 17) solves the distribution problem, but performing full RSA operations on an embedded MCU is computationally expensive.
Implementing Ephemeral ECDH
To establish a secure channel, we use Ephemeral Diffie-Hellman (EDH), specifically using Elliptic Curves (ECC) due to their smaller key sizes and lower CPU overhead compared to RSA. The "ephemeral" part is critical: the keys used for the exchange are discarded after the session ends, providing Perfect Forward Secrecy (PFS). If a long-term device key is stolen later, the attacker still cannot decrypt past captured sessions.
The exchange follows this logic:
- Device A generates a random private key
dAand calculates public keyQA = dA * G(whereGis the base point). - Device B generates a random private key
dBand calculates public keyQB = dB * G. - They exchange
QAandQBover the insecure link. - Both calculate the shared secret
S:- A computes:
S = dA * QB - B computes:
S = dB * QA - Because
(dA * dB) * Gresults in the same coordinate on the curve, both arrive at the sameS.
- A computes:
Simplified Logic
// Both sides agree on Curve25519 parameters
// Device A sends public_A; Device B sends public_B
uint8_t shared_secret[32];
// Perform Scalar Multiplication using a hardware accelerator (Lesson 24)
ecc_compute_shared_secret(my_private_key, peer_public_key, shared_secret);
// Derive session key using a KDF (Key Derivation Function)
uint8_t session_key[16];
hkdf_extract_and_expand(shared_secret, salt, "session_key_info", session_key);
By hashing the resulting S through a Key Derivation Function, you obtain a cryptographically strong session key. You then use this key with your symmetric block cipher (Lesson 15) to encrypt the actual telemetry data, ensuring efficiency while maintaining robust security.
Key Takeaway: Ephemeral Diffie-Hellman allows two devices to derive a shared secret over a public channel without ever transmitting the secret itself, providing perfect forward secrecy for your IoT communication.