Choose Between E2 and E3: Determine when to use gateway-terminated vs end-to-end encryption
In 60 Seconds
E2 encryption protects sensor data from device to gateway using unique per-device AES keys, ensuring that even compromised intermediate routing nodes cannot read the payload.
For Beginners: E2: Device-to-Gateway Encryption
Cryptography for IoT is the science of keeping sensor data and device commands secret and tamper-proof. Think of it as the digital equivalent of secret codes, locked boxes, and wax seals. Even if someone intercepts your IoT data traveling through the air, cryptography ensures they cannot read or alter it without the proper keys.
Sensor Squad: The Personal Sealed Envelope!
“E1 encryption is like everyone in the neighborhood sharing the same house key,” Sammy the Sensor explained. “But E2 is different – every device gets its OWN unique key that only it and the gateway share. It is like each of us having a personal sealed envelope that only the gateway can open.”
Max the Microcontroller nodded. “With E2, even the other sensors in the network cannot read Sammy’s data as it passes through them. The message hops from device to device, still wearing its E1 link-layer armor on each hop, but inside, the E2 encryption keeps the actual data secret from everyone except the gateway.”
“Replay attacks are a sneaky trick where a bad guy records a legitimate message and sends it again later,” Lila the LED warned. “Imagine someone recording Sammy saying ‘temperature is 20 degrees’ and replaying it over and over. The gateway would think the temperature is always 20! E2 stops this with sequence numbers – each message gets a unique number, so replayed old messages get rejected.”
“The tradeoff is that E2 uses more energy than E1 because each device needs its own encryption keys and sequence counters,” Bella the Battery explained. “But the security benefit is huge – if one device gets compromised, only THAT device’s key is exposed, not the entire network. It contains the damage to a single device!”
9.2 Introduction to E2 Device-to-Gateway Encryption
Time: ~10 min | Level: Intermediate | Unit: P11.C08.U03
E2 (Device-to-Gateway) encryption ensures authenticity and prevents intermediate nodes from reading data using unique per-device keys.
Figure 9.1: Device to gateway encryption (E2)
Purpose: Ensure authenticity and prevent intermediate nodes from reading data.
Characteristics:
Each node has unique private key
Gateway stores all node keys
AES-256 encryption at application layer
Combined with E1 (double encryption)
Includes sequence number + checksum for integrity
Figure 9.2: E2 device-to-gateway encryption showing multi-hop sensor network where each device has unique AES-256 key paired with gateway
9.3 E2 Implementation Details
Algorithm: AES-256 in CBC mode with integrity protection
Packet Structure:
Figure 9.3: E2 packet structure showing device ID header, sequence number for replay protection, encrypted payload, and HMAC-SHA256 for integrity
Key Management Complexity: Gateway must store N device keys
Attack Mitigations:
Attack Type
Mitigation
Replay Attack
Sequence number validation - gateway rejects old sequences
Tampering
HMAC-SHA256 - any modification invalidates authentication tag
Spoofing
Unique device keys - attacker cannot impersonate without key
Man-in-Middle
Combined with E1 - ensures packet origin authenticity
9.4 E2 vs E3: When to Use Each
Tradeoff: E2 (Device-to-Gateway) vs E3 (End-to-End) Encryption
Option A (E2 - Device-Gateway): Gateway decrypts data for local processing, enables edge analytics (reduce cloud bandwidth by 60-80%), allows gateway-based anomaly detection, requires trusted gateway hardware, 5-10ms processing latency at gateway.
Option B (E3 - End-to-End): Data encrypted from device to cloud, gateway only forwards opaque packets, zero-trust architecture (gateway compromise doesn’t leak data), prevents edge processing, adds 2-5ms encryption overhead per hop.
Decision Factors: Choose E2 when gateway is physically secured and local processing reduces bandwidth costs (industrial monitoring, smart buildings). Choose E3 when gateway is in semi-public location (retail, outdoor), when regulatory compliance requires end-to-end encryption (HIPAA, PCI-DSS), or when gateway vendor isn’t fully trusted.
9.5 E1-E5 Benefits Mapping
What Each Encryption Level Actually Protects
Each encryption level (E1-E5) solves specific security problems. Understanding the mapping helps you choose the right combination:
Level
Encrypts
Security Guarantee
Threat Mitigated
E1
Link layer
Access control
Unauthorized network join
E2
Device-Gateway
Authentication + Confidentiality
Eavesdropping on local network
E3
Device-Cloud
End-to-end confidentiality
Untrusted gateway
E4
Gateway-Cloud
Web-grade TLS
Internet eavesdropping
E5
Key renewal
Long-term key freshness
Key compromise over time
9.5.1 Common Combinations
Scenario
Recommended Levels
Why
Trusted gateway
E1 + E2 + E4
Gateway can decrypt; cloud link protected
Untrusted gateway
E1 + E3 + E4
Data stays encrypted through gateway
Long deployment
+ E5
Keys rotated to prevent compromise
9.5.2 Key Insight: The Untrusted Gateway Problem
In many IoT deployments, the gateway may be in a semi-public location (factory floor, retail store). Using E3 instead of E2 means:
Gateway cannot read sensor data (only forwards encrypted packets)
Compromised gateway cannot leak sensitive information
Trade-off: Gateway cannot do local processing/filtering
9.6 Encryption Layer Selection
Interactive Decision Framework
This decision tree helps select appropriate encryption layers based on deployment characteristics:
Figure 9.4: Encryption layer selection decision tree for IoT deployments
Concept: Understanding which encryption layer to use based on trust model and data sensitivity.
Tradeoff: Full Payload Encryption vs Selective Field Encryption
Option A (Full Payload Encryption): Encrypt entire message body (header + data), maximum confidentiality, 100% overhead on payload size with authenticated encryption modes, gateway cannot route based on content, simpler key management (one key per device-cloud pair).
Option B (Selective Field Encryption): Encrypt only sensitive fields (e.g., patient vitals, GPS coordinates), routing metadata remains readable, 20-40% overhead on sensitive fields only, enables edge-based filtering and aggregation, requires field-level key management (complexity 3x higher).
Decision Factors: Choose full encryption for high-security applications where any metadata leakage is unacceptable (medical devices, personal tracking). Choose selective encryption when edge processing is critical and only specific fields contain sensitive data (smart meters where timestamps are public but usage is private, fleet tracking where route is sensitive but vehicle status is not).
9.8 Worked Example: Securing a Smart Factory Floor Network
Scenario: A factory deploys 2,000 vibration sensors on CNC machines, each reporting 50-byte readings every second to an ESP32 gateway over IEEE 802.15.4 (6LoWPAN). The gateway aggregates data and forwards to the factory’s on-premises server. Design the E2 encryption layer and calculate the overhead.
Battery: AA lithium (3,000 mAh), 3-year target life
Gateway: ESP32 with 4 MB Flash, manages up to 500 sensors
Network: 6LoWPAN with 127-byte maximum frame size
Threat: Disgruntled employee with physical access to network
Step 1: E2 Packet Overhead Calculation
The raw sensor payload is 50 bytes. Calculate the E2 packet size:
Field
Size (bytes)
Purpose
Device ID
2
Identifies source sensor (supports up to 65,535 devices)
Sequence Number
4
Replay protection (wraps after 4.3 billion messages)
AES-256-CBC IV
16
Initialization vector (random per message)
Encrypted Payload
64
50 bytes padded to next 16-byte block (PKCS#7)
HMAC-SHA256
32
Message authentication (truncated to 16 bytes in constrained variant)
Total E2 packet
118 bytes
Fits within 127-byte 6LoWPAN frame
Overhead: 118 - 50 = 68 bytes (136% overhead). If using truncated HMAC (16 bytes), total drops to 102 bytes (104% overhead). Both fit the 127-byte frame limit.
Step 2: Energy Cost per Encrypted Message
AES-256-CBC encryption (64 bytes, Cortex-M0+):
Key expansion: 1.2 us @ 48 MHz
CBC encrypt (4 blocks): 4 x 2.8 us = 11.2 us
Total AES time: 12.4 us @ 18 mA = 0.74 uJ
HMAC-SHA256 (86 bytes input: 2 + 4 + 16 + 64 header+IV+ciphertext):
Two SHA-256 passes: 2 x 15 us = 30 us @ 18 mA = 1.8 uJ
Total E2 encryption per message: 2.54 uJ
Compare to 802.15.4 radio transmission:
TX at 0 dBm: 17.4 mA for 4.3 ms (127 bytes @ 250 kbps) = 238 uJ
E2 encryption overhead: 2.54 / 238 = 1.07% of radio cost
Step 3: Gateway Key Storage Requirements
The gateway must store one AES-256 key per sensor plus metadata:
Per sensor: 32 bytes (key) + 2 bytes (device ID) + 4 bytes (last sequence) = 38 bytes
500 sensors: 38 x 500 = 19,000 bytes = 18.6 KB
ESP32 has 4 MB Flash, 520 KB SRAM
Key database fits easily in NVS (Non-Volatile Storage) partition
Lookup time: O(1) with hash table on device ID
Step 4: Sequence Number Exhaustion Analysis
At 1 message per second, a 4-byte sequence number lasts:
2^32 messages / (1 msg/sec x 86,400 sec/day) = 49,710 days = 136 years
No sequence rollover concern for any practical deployment lifetime.
Result: E2 encryption adds only 1% energy overhead to radio transmission, fits within the 6LoWPAN frame limit, and the gateway can manage 500 sensors with under 19 KB of key storage. The 3-year battery target is unaffected by E2 encryption – radio transmission dominates energy consumption at 99:1.
Real-World Case Study: Norsk Hydro Factory Attack (2019)
In March 2019, the LockerGoga ransomware attack on Norwegian aluminum manufacturer Norsk Hydro caused $75 million in damages. While primarily an IT attack, the factory’s OT network shared credentials with IT systems – no per-device E2 encryption existed between sensors and the SCADA gateway. Once attackers reached the gateway, they could read and manipulate all sensor traffic in plaintext.
Had E2 encryption been deployed with per-device keys, compromising one sensor or the IT network would not have given attackers access to other sensors’ data streams. The per-device key architecture contains blast radius – exactly the property E2 is designed to provide.
Key lesson: E2 encryption is not just about confidentiality; the per-device key architecture provides damage containment. In a fleet of 2,000 sensors, compromising one device exposes only that device’s key, not the entire network. This containment property is worth the 68-byte overhead.
Step 3: Energy consumption - Total time: \(5.83 + 15 = 20.83\text{ µs}\) - Power: \(P = V \times I = 3.3\text{V} \times 0.018\text{A} = 59.4\text{ mW}\)
\[E = P \times t = 59.4 \times 10^{-3} \times 20.83 \times 10^{-6} = 1.24\text{ µJ}\]
Result: E2 encryption consumes 1.24 µJ per 32-byte message. For 1 message/minute, daily energy is \(1.24 \times 1440 = 1.78\) mJ.
In practice: On AA battery (10,000 J capacity), E2 crypto allows \(10,000 / (1.78 \times 10^{-3} \times 365) = 15,400\) years of operation (crypto is negligible vs radio transmission at ~238 µJ/message).
Match the E2 Security Feature
Key Concepts
E2 Encryption: Application-layer encryption from each IoT sensor to the gateway using unique per-device keys; intermediate nodes forward encrypted data without reading it.
Per-Device Key: A unique cryptographic key assigned to each individual device, so compromise of one device’s key does not expose other devices’ data.
Sequence Number: A monotonically increasing counter included in each encrypted packet to detect and reject replayed (replicated old) messages.
Replay Attack: An attack where an adversary captures a legitimate message and retransmits it later to trick the receiver; prevented by sequence numbers or timestamps.
Double Encryption: Combining E1 (link-layer) and E2 (device-to-gateway) encryption for layered protection — E1 protects each hop, E2 protects the full path.
AES-256-CBC: AES in Cipher Block Chaining mode with 256-bit key — provides confidentiality with chained block dependency; requires a random IV per message.
Key Store: A secure repository at the gateway that holds the unique encryption keys for each registered device.
Order the E2 Encryption Process
Place the steps of E2 device-to-gateway encryption in the correct order:
Common Pitfalls
1. Reusing Sequence Numbers After Device Reset
If a device resets its sequence counter to zero, an attacker can replay old packets until the counter catches up. Store the last sequence number in non-volatile memory or use a time-based nonce to survive reboots.
2. Storing All Device Keys in a Single Unprotected Database
A flat key store where all device keys are accessible to any process creates a single point of failure. Partition the key store and use hardware security modules (HSMs) for key storage at the gateway.
3. Not Validating the IV on Reception
Accepting any IV without checking for reuse allows attackers to force IV reuse, breaking CBC confidentiality. Maintain a short window of recently seen IVs and reject duplicates.
Label the Diagram
💻 Code Challenge
9.10 Summary
This chapter covered E2 device-to-gateway encryption:
E2 Purpose: Per-device keys ensure authenticity and prevent intermediate nodes from reading data
Packet Structure: Device ID + sequence number + AES IV + encrypted payload + HMAC-SHA256 tag
Continue to E3-E4: Transport and End-to-End Encryption to learn how device-to-cloud encryption (E3) enables use of untrusted gateways, and how TLS (E4) provides industry-standard transport security.