Chapters

13 E2: Device-to-Gateway Encryption

cryptography
encryption
device
gateway

In 60 Seconds

Name the Place Where Plaintext Returns

Picture a sealed sensor message reaching a local controller that must read it before switching a fan. A gateway means the trusted device or service that joins systems and, in this design, ends the protected device link.

Name the device identity, protected message, gateway key, freshness value, plaintext owner, and next route. Test a valid message, a changed message, a replay, and a gateway that should only forward.

Keep the envelope, verification result, counter, action, and trust boundary. This proves one device-to-gateway design, not privacy beyond that gateway; the deeper sections compare packet structure, replay defense, key handling, and later protection layers.

E2 protects messages from a device to a trusted gateway. Each device has its own credential, the gateway verifies freshness and authenticity before decrypting, and intermediate routers only forward ciphertext. E2 is the right fit when the gateway is allowed to read payloads for local control or filtering. If the gateway must not see plaintext, the design belongs in E3 device-to-cloud or object-level protection instead.

Picture a building sensor handing a sealed work order to the floor gateway. E2 is the design where that gateway is the approved desk that opens the envelope, checks the sender, rejects stale copies, and acts locally. If the gateway should only forward the envelope without reading it, this page has already taught the most important lesson: choose E3 instead.

13.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Explain exactly where E2 encryption terminates and which component owns plaintext.
  • Design an E2 packet envelope with per-device identity, nonce or counter, authenticated metadata, ciphertext, and tag.
  • Define replay protection that survives reset, sleep, loss, and gateway restart.
  • Decide when a trusted gateway justifies E2 and when an untrusted gateway requires E3.
  • Specify release evidence for key provisioning, gateway key storage, negative tests, rotation, and revocation.

13.2 Prerequisites

13.3 Choose E2 Only When the Gateway May Read

E2 is not the same thing as end-to-end device-to-cloud encryption. In E2, the gateway is trusted to authenticate and decrypt device payloads. That makes E2 useful for local automation, filtering, aggregation, and safety actions, but it also means gateway compromise can expose data for devices whose keys the gateway can access. Inspect Figure 13.3 to locate the exact point where ciphertext becomes plaintext before accepting that trust choice. Read Figure 13.1 in that order.

Device-to-gateway E2 trust boundary showing per-device ciphertext through routers and plaintext only inside the trusted gateway.
Figure 13.1: E2 protects the full device-to-gateway path, then intentionally terminates at the trusted gateway.

Follow Figure 13.3 from the device, through intermediate routers, to the trusted gateway. The payload stays encrypted while the routers forward it, but the gateway terminates E2 and may read it. That final plaintext boundary is what enables local action and creates the gateway-compromise risk. The next design step is therefore to scope gateway access and device keys deliberately, not to describe the whole path loosely as end-to-end encryption. Read Figure 13.1 in that order.

Per-device trust

Each device has its own key

One extracted device credential should not let an attacker impersonate the rest of the fleet.

Trusted gateway

The gateway may read payloads

The gateway can validate, decrypt, filter, aggregate, and act locally because it is a plaintext owner.

Freshness

Old packets must fail

Counters, nonces, epochs, or protocol replay windows prove that a message is new enough to accept.

Boundary

E2 is not zero trust

If the gateway is third-party, semi-public, or outside your control, route sensitive payloads to E3.

Plaintext Owner

In E2, the gateway is an approved plaintext owner. If that sentence is not acceptable for the deployment, do not use E2 for that payload.

13.4 Build the Packet So the Gateway Can Prove It

An E2 packet should make the receiver prove three facts before it releases plaintext: which device sent it, whether the message is fresh, and whether the protected bytes were modified. Use Figure 13.2 to inspect where each proof travels and why the gateway must validate the envelope before exposing the decrypted payload.

E2 packet envelope with device identity, key identifier, counter or nonce, authenticated metadata, ciphertext, and authentication tag.
Figure 13.2: The gateway should authenticate metadata and freshness before accepting device plaintext.

Read Figure 13.2 from the device identifier and key identifier into the counter or nonce, authenticated metadata, ciphertext, and final authentication tag. Identity selects the expected device and key scope; freshness state rejects an old envelope; authenticated metadata binds visible routing context to the protected message; and the tag detects modification before plaintext is accepted. This packet structure turns the E2 trust boundary into a reviewable receive procedure rather than a claim that encryption is present.

Field
Protects
Gateway role
Review evidence
Device identity
Maps the message to the enrolled device and its current key material.
Looks up the device record before verification and avoids trusting a self-claimed name by itself.
Unknown device IDs, disabled devices, and swapped device IDs are rejected.
Key identifier or epoch
Separates old and new keys during rotation and recovery.
Selects the expected key version without guessing or trying every key in the database.
Old, retired, and future key epochs fail according to policy.
Nonce or counter
Prevents replay and avoids nonce reuse under the same key.
Maintains accepted counter state, replay windows, or protocol-specific freshness state.
Replayed, rolled-back, duplicated, and out-of-window packets are rejected.
AAD metadata
Authenticates headers that must remain readable for routing or policy decisions.
Verifies metadata before trusting message type, device class, route, or priority.
Tampering with any authenticated header causes verification failure.
Ciphertext and tag
Provides confidentiality and integrity for the protected payload.
Releases plaintext only after the authentication tag verifies.
Modified payloads, wrong keys, truncated tags, and wrong algorithms fail closed.
Prefer a Reviewed AEAD Envelope

For new designs, prefer an authenticated encryption mode or protocol profile that binds associated data, nonce, ciphertext, and tag. Do not invent a custom CBC/HMAC packet unless a reviewed protocol, library, and test suite already define the exact composition and failure behavior.

13.5 Make Freshness Survive Reboots and Loss

Replay protection is not just a sequence number field. The device, gateway, and recovery process must agree what happens after sleep, reset, packet loss, clock drift, key rotation, and gateway failover.

Device stores send state

Persist enough counter, epoch, or nonce state so reboot does not reuse values under the same key.

Gateway stores accept state

Record the last accepted counter, replay window, or protocol state per device and per key epoch.

Loss is expected

Use a bounded acceptance window only when the protocol can tolerate out-of-order delivery.

Rotation changes epoch

Make old and new keys distinguishable so counters do not collide across key updates.

Failures are observable

Log replay, tag failure, unknown device, expired key, and rollback events without leaking secrets.

Nonce reuse under the same key can break common AEAD security assumptions. A production design must specify how nonce or counter uniqueness is maintained, measured, and tested.

13.7 Choose Credentials the Device Can Protect

Certificate-based DTLS can be appropriate when devices can store and validate certificates and the deployment needs PKI-style identity management. Very small sensors may instead use raw public keys or a pre-shared key profile. PSK mode avoids certificate-chain storage and heavy certificate validation on the device, but it moves the hard work into provisioning and lifecycle evidence.

The PSK must identify one device or a tightly bounded derivation path, not the whole fleet. A single shared firmware secret turns one extracted device into a fleet-wide compromise. A good E2 review therefore pairs the authentication mode with key ownership, storage, rotation, and revocation evidence.

Certificate mode:
  Strong PKI identity model, but heavier certificate storage and validation.

Raw public key:
  Lighter than a certificate chain, but still needs enrollment and pinning policy.

Pre-shared key:
  Small device footprint, but only safe when keys are per-device and rotatable.
PSK Mode

13.8 Prove DTLS Survives Spoofing, Sleep, and Rotation

UDP lets an attacker spoof source addresses more easily than TCP. A DTLS gateway should not allocate expensive handshake state or amplify traffic toward a victim until the client proves it can receive packets at the claimed address. The stateless cookie exchange does that: the gateway returns a cookie, and the client must echo it before the gateway commits more resources.

Battery life is the other deployment issue. Sleepy devices should not repeat full handshakes every time they wake if the protocol and risk model allow resumption. Session resumption reduces round trips and computation, but the release evidence must still prove replay windows, credential expiry, key updates, and revoked-device behavior.

DTLS concern
Protects
Gateway role
Review evidence
Stateless cookie
Gateway CPU and bandwidth during spoofed-source traffic.
Issues a return-routability challenge before allocating handshake state.
Spoofed-source handshakes fail without creating persistent gateway state or amplification.
Retransmission
Handshake completion on lossy local links.
Handles timeout and retransmit policy without accepting duplicate application commands.
Loss, reorder, and duplicate handshake tests complete or fail closed according to policy.
Session resumption
Battery and latency for devices that sleep and reconnect.
Resumes only for valid device state, key epoch, and authorization status.
Expired, rotated, revoked, and replayed resumed sessions fail according to documented policy.
DTLS Cookie Exchange

13.9 Choose E2, E3, or E4 by Plaintext Ownership

  1. Shield Shelly maps device, gateway, and cloud, then marks only the approved plaintext readers.

    First, name everyone allowed to read the plain data.

  2. Shelly chooses among a trusted decrypting gateway, an opaque gateway, and a gateway-started protected session.

    Choose the layer that keeps that exact boundary.

  3. Shelly tests keys and shows an unapproved reader refused while the approved path works.

    Test the keys and refuse readers outside it.

CP-0067 decision strip: Choose E2 only when gateway plaintext is part of the approved design.

E2, E3, and E4 answer different trust questions. The right answer depends on who may see plaintext, not on which name sounds stronger. Inspect Figure 13.1 before selecting a layer so the gateway’s approved role remains explicit. Read Figure 13.3 in that order.

Decision matrix comparing E2 trusted gateway, E3 opaque gateway, and E4 gateway-to-cloud transport protection.
Figure 13.3: Choose E2 only when gateway plaintext is part of the approved design.

Read Figure 13.1 by plaintext ownership. The E2 path ends at a trusted gateway that verifies and decrypts device data; the E3 path keeps the selected payload opaque until the cloud or application endpoint; and E4 protects an authenticated transport session, which may begin at the gateway after it has already seen plaintext. That comparison connects the layer labels to a concrete review question: name every permitted reader first, then require keys and negative tests for that boundary. Read Figure 13.3 in that order.

Layer
Protects
Gateway role
Review evidence
E2 device-gateway
Device payloads across local routers until the trusted gateway verifies and decrypts them.
Plaintext owner, local validator, aggregator, controller, or safety actor.
Gateway key store controls, per-device keys, replay rejection, tag failure tests, and local action policy.
E3 device-cloud
Payloads that must remain opaque through gateways, brokers, queues, or proxies.
Forwarder only; it should not have payload keys.
Gateway cannot decrypt test payloads; cloud rejects tampered objects and wrong device identity.
E4 transport
The gateway-to-cloud or device-to-service transport session.
Authenticated session endpoint for TLS, DTLS, MQTT over TLS, HTTPS, or CoAP over DTLS.
Certificate identity validation, version policy, expired/revoked credential behavior, and downgrade tests.

13.10 E2 Is Appropriate When

Review the evidence as an ordered release decision. First verify The gateway is owned, hardened, monitored, and revocable. Then verify Local automation or safety response needs plaintext during cloud outage. Then verify Filtering, aggregation, compression, or protocol translation is a required gateway function. Then verify Device-level revocation matters more than keeping the gateway blind. Finally verify The gateway key store is treated as sensitive production infrastructure.

13.11 Treat the Gateway Key Store as the Boundary

The E2 gateway is both a verifier and a key holder. Its key store is therefore part of the security boundary, not a normal configuration file.

Provision

Enroll unique device credentials

Manufacturing, commissioning, or onboarding should create one device identity and one active E2 key record per device.

Store

Limit gateway key access

Use protected storage, process isolation, service identity, audit logs, and least privilege for gateway key lookups.

Rotate

Support overlap and retry

Rotation needs key epochs, rollback-safe activation, and recovery from devices that miss an update window.

Revoke

Contain one-device compromise

Disable one device key without replacing every other device or accepting unauthenticated fallback messages.

Shared Fleet Keys Break E2

If every device uses the same E2 key, the gateway cannot identify which device really sent a message, and one extraction becomes a fleet compromise. E2 depends on per-device accountability.

13.12 Build the Trusted Building Gateway Case

Scenario

A building operator owns temperature and occupancy sensors, floor gateways, and the cloud tenant. Gateways run local HVAC safety logic during cloud outages, so they are approved to read operational payloads. Visitor-count payloads are sensitive and should remain opaque to the gateway.

13.12.1 Step 1: Split Payloads by Plaintext Owner

Payload
Protects
Gateway role
Review evidence
Temperature telemetry
Operational readings needed for local control and alarms.
Trusted plaintext owner that validates E2 and triggers local HVAC logic.
Per-device E2 keys, replay rejection, tag failure tests, and gateway action logs.
Occupancy safety event
Local safety state needed during cloud outage.
Trusted plaintext owner for local response only.
Gateway policy limits storage, logging, and forwarding of decrypted fields.
Visitor count analytics
Sensitive aggregate data that the gateway does not need to inspect.
Forwarder only.
Use E3 object protection; gateway cannot decrypt sample payloads.
Gateway-cloud session
Internet transport after local validation and routing.
TLS or DTLS endpoint.
E4 identity validation and credential lifecycle tests.

13.12.2 Step 2: Approve the E2 Envelope

Work through the sequence from the first action to the final observation. Begin with Use one enrolled E2 credential per device, with key epoch and rotation state. Then Put device identity, message type, key epoch, route, and counter in authenticated metadata when they need to remain readable. Then Use the selected AEAD mode or reviewed envelope exactly as specified by the platform or protocol. Then Verify the tag before decrypting or using payload fields. Then Reject replayed, rolled-back, duplicated, wrong-key, wrong-device, and wrong-epoch messages. End by Log security failures without storing decrypted secrets unnecessarily.

13.12.3 Step 3: Define Release Evidence

Release evidence must cover these checks. An unknown device is rejected before payload processing. A valid device with the wrong key fails authentication. Tampered authenticated metadata fails verification. A replayed counter or nonce is rejected. Device reboot does not reuse nonce or counter values under the same key. Gateway restart preserves or reconstructs replay state safely. A retired key epoch is rejected after the rotation window closes. Revoking one device does not affect unrelated devices. The sensitive visitor-count payload is routed to E3 and remains opaque to the gateway. Operational logs distinguish unknown device, replay, tag failure, expired key, and policy rejection.

13.13 Avoid the E2 Mistakes That Expose Plaintext

Mistake

Calling E2 end-to-end

E2 terminates at the gateway. Do not use E2 for payloads the gateway must not read.

Mistake

Using one fleet key

A shared E2 key removes device accountability and turns one extracted key into a fleet-wide incident.

Mistake

Reusing nonces after reset

Sleep and reset behavior must not cause nonce or counter reuse under the same key.

Mistake

Decrypting before verification

The gateway should authenticate the envelope and freshness before releasing plaintext to application logic.

Mistake

Ignoring gateway compromise

If gateway compromise is in scope, use E3 for sensitive fields or remove plaintext duties from the gateway.

Mistake

No key replacement path

A device key must be rotatable, revocable, and recoverable without insecure accept-anything modes.

13.14 Knowledge Check

Gateway Trust Decision
Match E2 Controls to Evidence
Order the Gateway Receive Path
Label the E2 Evidence Path
Code Challenge

13.15 Release Evidence Checklist

Before production, an E2 design should be reduced to testable evidence:

Review the evidence as an ordered release decision. First verify The gateway is explicitly approved as a plaintext owner for each E2 payload. Then verify Sensitive fields the gateway must not inspect are routed to E3 or object protection. Then verify Each device has unique active key material or a unique path to derive it. Then verify Device identity, message type, key epoch, counter or nonce, and routing metadata are authenticated as required. Then verify Nonce or counter uniqueness is defined across reset, sleep, packet loss, and key rotation. Then verify Gateway key access is isolated, audited, and backed by least privilege. Then verify Unknown device, wrong key, bad tag, tampered metadata, replay, expired epoch, revoked device, and rollback tests fail closed. Then verify Rotation supports overlap, retry, recovery, and retirement of old epochs. Then verify Operational logs distinguish security failures without storing decrypted secrets unnecessarily. Finally verify Measurements use representative hardware, packet size, radio duty cycle, and gateway load rather than copied benchmark numbers.

13.17 What’s Next

Continue with E3-E4: Transport Encryption to separate opaque device-to-cloud payload protection from authenticated gateway-to-cloud transport.

Next ChapterUse it for
E3-E4: Transport EncryptionDevice-to-cloud object protection and TLS/DTLS transport decisions
E5: Key Renewal and AsymmetricRotation, revocation, and long-lived credential renewal
Key ManagementStorage, ownership, key derivation, and operational lifecycle

13.18 Summary

Device-to-gateway encryption protects data as it moves from constrained devices into local gateways. It must account for local attackers, shared network media, gateway trust, credential storage, and what happens when gateways relay data onward.

13.19 Key Takeaway

Device-to-gateway security should define both ends of trust. Encrypt the link, authenticate the device and gateway, and decide whether the gateway is allowed to see plaintext or only forward protected payloads.