4  Cryptography for IoT

4.1 Learning Objectives

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

  • Implement symmetric encryption (AES) for IoT data protection
  • Apply asymmetric encryption (RSA, ECC) for key exchange and digital signatures
  • Verify message integrity using cryptographic hash functions (SHA-256, BLAKE2)
  • Select appropriate cryptographic algorithms based on device constraints
  • Implement HMAC for authenticated messages
In 60 Seconds

IoT cryptography applies symmetric encryption (AES) for fast bulk data protection and asymmetric encryption (ECC/RSA) for secure key exchange, with hash functions (SHA-256) ensuring data integrity across resource-constrained devices.

What is Cryptography? Cryptography is the science of protecting information by transforming it into an unreadable format (encryption) that can only be converted back (decryption) by someone with the correct key. It’s like a secret code that only authorized parties can understand.

Why does it matter for IoT? IoT devices transmit sensitive data (health readings, location, home activities) over networks where attackers can intercept traffic. Cryptography ensures that even if attackers capture the data, they cannot read or modify it.

Key terms: | Term | Definition | |——|————| | Encryption | Converting readable data (plaintext) into unreadable format (ciphertext) | | Decryption | Converting ciphertext back to plaintext using a key | | Symmetric encryption | Same key for encryption and decryption (fast, for bulk data) | | Asymmetric encryption | Different keys for encryption (public) and decryption (private) | | Hash function | One-way function that creates a fixed-size fingerprint of data |

“I need to send my temperature reading to Max, but the network is not safe!” Sammy the Sensor worried. “Anyone listening could steal my data!”

Max the Microcontroller smiled. “That is what cryptography is for! Think of it like a secret code between friends. With symmetric encryption, we both share the same secret key – like a codebook that only we have. I scramble my message using the key, send it, and you unscramble it with the same key. It is super fast, which is perfect for us IoT devices with limited power.”

“But how do you share the codebook safely in the first place?” Lila the LED asked. “That is where asymmetric encryption comes in! You create TWO keys – a public key and a private key. Anyone can use your public key to lock a message, but ONLY your private key can unlock it. It is like a mailbox slot: anyone can drop a letter in, but only you have the key to open it.”

“And hash functions are like fingerprints!” Bella the Battery added. “Feed any data into a hash function, and you get a unique fixed-size fingerprint. Change even one tiny bit of the data and the fingerprint looks completely different. So when Sammy sends data with its hash, Max can verify nothing was tampered with along the way. Secret codes, locked mailboxes, and fingerprints – that is cryptography in a nutshell!”

4.2 Prerequisites

Before diving into this chapter, you should be familiar with:

Key Concepts
  • Symmetric Encryption: Encryption where the same secret key is used for both encryption and decryption; fast and suitable for bulk IoT data (e.g., AES-128-GCM).
  • Asymmetric Encryption: Encryption using a public/private key pair; the public key encrypts, the private key decrypts. Used for key exchange and digital signatures (e.g., RSA, ECC).
  • AES-GCM: Advanced Encryption Standard in Galois/Counter Mode — provides both encryption and authentication in one operation, widely used in IoT.
  • HMAC: Hash-based Message Authentication Code — combines a cryptographic hash with a secret key to authenticate messages and detect tampering.
  • SHA-256: A 256-bit cryptographic hash function producing a fixed-size fingerprint of data; even a 1-bit change in input produces a completely different output.
  • ECC (Elliptic Curve Cryptography): A form of public-key cryptography offering equivalent security to RSA with much smaller key sizes, making it ideal for constrained IoT devices.
  • Nonce / IV: A number used once (nonce) or initialization vector — a unique random value that must never be reused with the same key to prevent cryptographic attacks.

4.3 How It Works: AES-GCM Authenticated Encryption

AES-GCM (Galois/Counter Mode) combines encryption and authentication in a single operation:

Encryption Phase:

  1. Generate random IV (Initialization Vector): 12 random bytes (MUST be unique per message)
  2. Counter mode encryption: AES encrypts counter values (0, 1, 2…) to create keystream
  3. XOR with plaintext: Plaintext ⊕ keystream = ciphertext (reversible)
  4. Galois authentication: Compute authentication tag over ciphertext + additional data

Decryption Phase:

  1. Verify authentication tag FIRST: Prevents processing tampered ciphertext
  2. If tag invalid: Reject message immediately, log potential attack
  3. If tag valid: Decrypt ciphertext using same IV and key
  4. Return plaintext: Only if authentication succeeded

Key Components:

  • Symmetric key (128/192/256-bit): Shared secret between sender and receiver
  • IV (nonce) (96-bit): Random value, different for EVERY message
  • Additional Authenticated Data (AAD): Unencrypted metadata also protected by tag
  • Authentication tag (128-bit): Proves message came from holder of key and was not modified

Real-World Example: ESP32 encrypting sensor data

Plaintext: "temperature=25.5,humidity=60"
Key: 128-bit AES key (pre-shared or negotiated via ECDH)
IV: Random 12 bytes generated per message
AAD: "sensor_id=42,timestamp=1735689600"

Process:
1. Generate random IV: 0xa3f8b2c1d4e5f6a7b8c9d0e1
2. Encrypt with AES-GCM → Ciphertext
3. Compute tag over (ciphertext + AAD)
4. Send: IV || ciphertext || tag (total +28 bytes overhead)

Receiver:
1. Extract IV, ciphertext, tag
2. Verify tag using key + IV + ciphertext + AAD
3. If valid → decrypt ciphertext
4. If invalid → reject (message tampered or wrong key)

Why GCM mode? Older modes (ECB, CBC) provide ONLY confidentiality. GCM provides confidentiality + integrity + authenticity. A message with flipped bits is detected and rejected BEFORE decryption.

4.4 Symmetric Encryption

Definition: Same key for encryption and decryption

Use Cases: Data confidentiality, session encryption, bulk data protection

Common Algorithms:

  • AES: Advanced Encryption Standard (128/192/256-bit)
  • ChaCha20: Fast on devices without AES hardware acceleration

4.4.1 How Symmetric Encryption Works

Plaintext → [Encryption Algorithm + Key] → Ciphertext
Ciphertext → [Decryption Algorithm + Same Key] → Plaintext

Advantages:

  • Very fast (50-100 MB/s on microcontrollers)
  • Low computational overhead
  • Suitable for constrained IoT devices

Challenges:

  • Key distribution: How do both parties get the same secret key?
  • Key storage: Where do you securely store the key on the device?

4.4.2 AES-128-GCM Implementation Example (ESP32)

// AES-128-GCM authenticated encryption for sensor data
#include "mbedtls/gcm.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/entropy.h"

mbedtls_gcm_context gcm;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_context entropy;
unsigned char key[16] = {0x2b, 0x7e, 0x15, 0x16, /* ... 16 bytes */};

void setup() {
  Serial.begin(115200);

  // Initialize random number generator
  mbedtls_entropy_init(&entropy);
  mbedtls_ctr_drbg_init(&ctr_drbg);
  mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
                         &entropy, NULL, 0);

  // Initialize AES-GCM
  mbedtls_gcm_init(&gcm);
  mbedtls_gcm_setkey(&gcm, MBEDTLS_CIPHER_ID_AES, key, 128);
}

bool encryptData(const uint8_t* plaintext, size_t len,
                 uint8_t* output, uint8_t* iv, uint8_t* tag) {
  // Generate random 12-byte IV (MUST be unique per message)
  mbedtls_ctr_drbg_random(&ctr_drbg, iv, 12);

  // Encrypt and compute authentication tag
  return mbedtls_gcm_crypt_and_tag(&gcm, MBEDTLS_GCM_ENCRYPT,
    len, iv, 12, NULL, 0, plaintext, output, 16, tag) == 0;
  // Send: IV (12 bytes) || ciphertext || tag (16 bytes)
}

4.4.3 AES Performance Comparison

Algorithm Speed (MB/s) Key Size Security Level IoT Suitability
AES-128 50-100 128-bit High Excellent
AES-256 40-80 256-bit Very High Good
ChaCha20 80-150 256-bit Very High Excellent (no HW accel)

When to use each:

  • AES-128: Default choice for most IoT applications
  • AES-256: High-security environments (medical, financial)
  • ChaCha20: Devices without AES hardware acceleration
Try It: Symmetric Cipher Throughput Estimator

Estimate how long it takes to encrypt a batch of IoT sensor readings with different symmetric ciphers and key sizes. Adjust the payload size and device clock speed to see the impact on throughput and latency.

4.5 Asymmetric Encryption

Definition: Different keys for encryption (public) and decryption (private)

Use Cases: Key exchange, digital signatures, authentication

Public key (asymmetric) encryption diagram showing the complete encryption and decryption workflow. On the sender side, an unencrypted plaintext message is processed through an encryption algorithm using the receiver's public key to produce encrypted ciphertext. The ciphertext travels across the network to the receiver, where the decryption algorithm uses the receiver's private key to recover the original plaintext message. Key insight: anyone can encrypt using the public key (freely distributed), but only the private key holder can decrypt, enabling secure communication without pre-shared secrets.
Figure 4.1: Source: University of Edinburgh IoT Security Course

Common Algorithms:

  • RSA: 2048/4096-bit keys
  • ECC: Elliptic Curve Cryptography (256-bit = RSA 3072-bit security)

4.5.1 How Asymmetric Encryption Works

Public Key: Can be shared with anyone
Private Key: Must be kept secret

Encryption: Plaintext + Public Key → Ciphertext
Decryption: Ciphertext + Private Key → Plaintext

Digital Signature:
Sign: Hash + Private Key → Signature
Verify: Signature + Public Key → Valid/Invalid

4.5.2 RSA Digital Signature Implementation

Signing – hash the firmware, then sign the hash with the private key:

// Sign firmware update with RSA (ESP32 / mbedTLS)
#include "mbedtls/pk.h"
#include "mbedtls/sha256.h"

bool signFirmware(const uint8_t* firmware, size_t len,
                   const uint8_t* private_key, uint8_t* signature) {
  mbedtls_pk_context pk;
  mbedtls_pk_init(&pk);
  mbedtls_pk_parse_key(&pk, private_key, key_len, NULL, 0);

  uint8_t hash[32];
  mbedtls_sha256(firmware, len, hash, 0);        // SHA-256 digest

  size_t sig_len;
  mbedtls_pk_sign(&pk, MBEDTLS_MD_SHA256, hash, 32,
                  signature, &sig_len, NULL, NULL); // RSA sign
  mbedtls_pk_free(&pk);
  return true;
}

Verification – recompute the hash and check the signature with the public key:

bool verifyFirmware(const uint8_t* firmware, size_t len,
                     const uint8_t* public_key, const uint8_t* signature) {
  mbedtls_pk_context pk;
  mbedtls_pk_init(&pk);
  mbedtls_pk_parse_public_key(&pk, public_key, key_len);

  uint8_t hash[32];
  mbedtls_sha256(firmware, len, hash, 0);

  int ret = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, hash, 32,
                               signature, sig_len);
  mbedtls_pk_free(&pk);
  return (ret == 0);
}

4.5.3 ECC vs RSA Comparison

Feature ECC (256-bit) RSA (2048-bit)
Key Size 256 bits 2048 bits
Signature Size 64 bytes 256 bytes
Speed Faster Slower
Security Equivalent Equivalent
IoT Suitability Excellent Good
Battery Impact Lower Higher

Recommendation: Use ECC (specifically Ed25519 or ECDSA P-256) for IoT devices due to smaller key sizes and faster operations.

Try It: ECC vs RSA Key Size and Performance Comparison

Compare how ECC and RSA scale with increasing security levels. Observe the dramatic difference in key sizes, signature sizes, and verification times – the reason ECC dominates IoT cryptography.

4.5.4 Cryptographic Algorithm Selection Guide

Cryptographic algorithm selection decision tree for IoT devices, branching on AES hardware acceleration availability, RAM constraints, regulatory requirements, and operational lifespan to recommend appropriate symmetric ciphers, asymmetric algorithms, and hash functions

Quick Reference:

  • Resource-constrained devices: Ed25519 + ChaCha20-Poly1305
  • TLS/DTLS compatible: ECDSA P-256 + AES-128-GCM
  • Maximum security: AES-256-GCM + ECDHE + Argon2id

4.6 Hash Functions

Definition: One-way functions that produce a fixed-size output (digest) from any input

Use Cases: Message integrity, password storage, checksums, digital signatures

Common Algorithms:

  • SHA-256: 256-bit hash, standard choice
  • SHA-3: Latest NIST standard
  • BLAKE2: Faster alternative to SHA-2

4.6.1 Properties of Good Hash Functions

Property Description Example
Deterministic Same input always produces same output SHA256(“hello”) always = 2cf24…
One-way Cannot reverse hash to get original input Cannot get “hello” from 2cf24…
Collision-resistant Hard to find two inputs with same hash SHA256(“a”) ≠ SHA256(“b”)
Avalanche effect Small input change = completely different output SHA256(“hello”) ≠ SHA256(“hellp”)

4.6.2 SHA-256 Implementation for Message Integrity

// SHA-256 for message integrity
#include "mbedtls/sha256.h"

String computeHash(const uint8_t* data, size_t len) {
  uint8_t hash[32];
  mbedtls_sha256(data, len, hash, 0);

  // Convert to hex
  String hashStr = "";
  for (int i = 0; i < 32; i++) {
    hashStr += String(hash[i], HEX);
  }
  return hashStr;
}

// Example usage
void verifyDataIntegrity() {
  String sensorData = "temperature=25.5,humidity=60";
  String hash = computeHash((uint8_t*)sensorData.c_str(), sensorData.length());

  Serial.println("Data: " + sensorData);
  Serial.println("Hash: " + hash);

  // Send both data and hash
  // Receiver computes hash and compares to verify integrity
}
Try It: Hash Avalanche Effect Explorer

Type two messages below to see how even a tiny change in input produces a completely different hash output. This demonstrates the avalanche effect – a critical property of cryptographic hash functions that makes them useful for integrity verification.

4.6.3 HMAC for Authenticated Messages

HMAC (Hash-based Message Authentication Code) combines a hash function with a secret key to provide both integrity AND authentication.

// HMAC for authenticated messages
#include "mbedtls/md.h"

bool computeHMAC(const uint8_t* data, size_t data_len,
                  const uint8_t* key, size_t key_len,
                  uint8_t* hmac) {
  mbedtls_md_context_t ctx;
  mbedtls_md_init(&ctx);
  mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);

  mbedtls_md_hmac_starts(&ctx, key, key_len);
  mbedtls_md_hmac_update(&ctx, data, data_len);
  mbedtls_md_hmac_finish(&ctx, hmac);

  mbedtls_md_free(&ctx);
  return true;
}

Hash vs HMAC:

Feature Hash (SHA-256) HMAC (HMAC-SHA256)
Integrity Yes Yes
Authentication No Yes
Requires secret key No Yes
Use case Verify data hasn’t changed Verify data came from authorized sender
Try It: HMAC Message Authentication Simulator

Simulate how HMAC protects IoT messages. See what happens when an attacker tries to tamper with the message or forge an authentication tag without the secret key.

Knowledge Check: Cryptography Selection

Question: An IoT temperature sensor needs to send encrypted readings every 30 seconds to a cloud server. Which cryptographic approach provides the BEST balance of security and performance?

A. RSA-2048 asymmetric encryption for all sensor readings B. SHA-256 hashing without encryption C. AES-128 symmetric encryption with periodic key rotation D. No encryption but send over HTTPS only

Click to reveal answer

Answer: C - AES-128 symmetric encryption with periodic key rotation

Why?

  • AES-128 is fast (50-100 MB/s), uses minimal CPU, and provides strong security
  • RSA is too slow for frequent encryption (every 30 seconds)
  • SHA-256 provides integrity but NOT confidentiality (anyone can read the data)
  • HTTPS adds overhead; a persistent encrypted MQTT session is more efficient

Periodic key rotation (e.g., daily) maintains security even if a key is compromised.

4.7 Per-Device vs Global Keys

Tradeoff: Per-Device Keys vs Global Keys

Option A (Global Key): All 1,000 sensors share one AES encryption key - Simpler key management - Single key to rotate - Risk: If ANY sensor is compromised, ALL sensor data is exposed

Option B (Per-Device Keys): Each sensor has unique AES key - More complex key management (1,000 keys) - Requires automated provisioning - Benefit: Compromised sensor only exposes that one device’s data

Decision: Always use per-device keys. The complexity is worth the isolation benefit. Modern IoT platforms (AWS IoT Core, Azure IoT Hub) enforce per-device credentials.

4.8 Case Study: Philips Hue Bridge Cryptographic Vulnerability (CVE-2020-6007)

In February 2020, researchers at Check Point discovered a vulnerability chain in the Philips Hue smart lighting ecosystem that demonstrated why cryptographic implementation details matter as much as algorithm selection.

The Setup: Philips Hue uses Zigbee (IEEE 802.15.4) with AES-128 encryption for bulb-to-bridge communication, and TLS 1.2 with ECC certificates for bridge-to-cloud. On paper, the cryptographic choices were sound.

The Vulnerability Chain:

Step Attack Cryptographic Failure
1 Exploit Zigbee touchlink commissioning (CVE-2017-15194) Touchlink used a known factory-default AES key for “easy pairing”
2 Compromise one Hue bulb with malicious firmware Firmware signed but bulb accepted unsigned Zigbee OTA updates
3 Trigger buffer overflow in bridge when processing bulb color data Bridge trusted AES-encrypted data without input validation
4 Gain root access to bridge on home network Bridge stored network credentials in plaintext flash

Impact Assessment:

  • Affected devices: Over 15 million Philips Hue bulbs and 3+ million bridges worldwide
  • Attack range: Zigbee radio range (~100m line of sight), extendable via compromised bulbs daisy-chaining
  • Consequence: Full home network access from a compromised light bulb
  • Patch timeline: Signify (Philips parent) released firmware 1935144040 within 2 weeks

Cryptographic Lessons:

Principle What Philips Did Wrong Correct Approach
Key management Factory-default touchlink key shared across all devices Per-device unique pairing keys generated during manufacturing
Firmware signing Zigbee OTA updates accepted without signature verification Require Ed25519/ECDSA signature on ALL firmware paths, not just cloud-to-bridge
Trust boundary Bridge trusted encrypted data from bulbs without validation Encrypt AND validate: AES protects confidentiality, but input sanitization prevents exploitation
Credential storage Wi-Fi password stored in plaintext on bridge flash Use hardware security module or encrypted keystore

Key lesson: The Philips Hue ecosystem used strong algorithms (AES-128, TLS 1.2, ECC) but made implementation errors that rendered the cryptography ineffective. A factory-default shared key is equivalent to no key. Signing firmware on one path but not another creates a bypass. Trusting encrypted data without validation confuses confidentiality with integrity. Cryptographic security requires correct implementation across every interface, not just the primary data path.

Scenario: You’re deploying 50 ESP32 temperature sensors in an industrial facility. Each sensor transmits data every 10 seconds to a cloud MQTT broker. You need to implement end-to-end encryption while minimizing CPU overhead on the constrained devices.

Implementation Steps:

  1. Symmetric Encryption for Bulk Data: Use AES-128-GCM (authenticated encryption) for sensor readings:
    • ESP32 has hardware AES acceleration → 50 MB/s throughput
    • Payload size: 64 bytes (timestamp + device_id + temperature + humidity)
    • Encryption overhead: ~1.3 ms per message
    • Battery impact: Minimal (0.02% of transmission energy)
  2. Asymmetric Key Exchange: Use ECDH (Elliptic Curve Diffie-Hellman) with P-256 curve for session key establishment:
    • Device generates ephemeral ECC key pair (256-bit)
    • Exchanges public keys with cloud server
    • Both derive shared secret (32 bytes), then use HKDF to produce AES-128 session key (16 bytes)
    • Key exchange time: ~8 ms on ESP32
    • Performed once per connection, reused for 1000+ messages
  3. Per-Device Unique Keys: Each ESP32 has unique device certificate (ECC P-256) burned into flash during manufacturing:
    • Device private key: stored in ESP32 flash encryption partition
    • Device public certificate: uploaded to cloud during provisioning
    • Cloud verifies device identity during TLS handshake
    • Compromising one sensor does NOT expose other 49 sensors

Performance Measurements (on ESP32 @ 240 MHz): - AES-128-GCM encryption: 1.3 ms per 64-byte payload - ECDH key exchange: 8 ms (once per session) - Total CPU time per message: 1.3 ms encryption + 0.4 ms TLS overhead = 1.7 ms - CPU utilization: (1.7 ms / 10,000 ms) × 100 = 0.017% per message - Power consumption: Encryption adds <0.5 mAh per day to battery

Cost-Benefit Analysis:

  • Security benefit: Prevents eavesdropping, replay attacks, data tampering
  • Performance cost: 1.7 ms CPU time per message (negligible on 10-second interval)
  • Implementation cost: ~$0.50 per device for ECC secure element (ATECC608)
  • Alternative cost: Data breach after sensor compromise = $50K+ in downtime and investigation

Result: With hardware-accelerated AES-128-GCM and ECDH key exchange, the ESP32 sensor network achieves strong encryption with less than 0.02% CPU overhead. The $25 additional cost ($0.50 x 50 devices) prevents potential $50K+ breach costs – a 2000x return on investment.

Interactive Encryption Overhead Calculator: Adjust parameters to see how encryption impacts your IoT deployment.

Selection Criteria Comparison Table:

Device Profile Symmetric Cipher Asymmetric Cipher Hash Function Best For Justification
High-End Gateway (1+ GHz CPU, 512+ MB RAM) AES-256-GCM RSA-2048 or ECC P-384 SHA-256 TLS 1.3 with full certificate chain Full cryptographic suite; supports all modern protocols
Microcontroller (160-240 MHz, 64-256 KB RAM) AES-128-GCM (hardware accel) ECC P-256 (ECDH/ECDSA) SHA-256 MQTT over TLS, CoAP over DTLS Hardware AES acceleration on ESP32/STM32; ECC has 10× smaller keys than RSA
Severely Constrained (<32 KB RAM, <8 MHz) ChaCha20-Poly1305 or AES-128-CCM Ed25519 BLAKE2s Custom lightweight protocols ChaCha20 is fast in software; Ed25519 is fastest signature algorithm
Sensor with Crypto Chip (TPM/ATECC608) AES-128 (in hardware) ECC P-256 (in hardware) SHA-256 Medical IoT, payment terminals Hardware security module prevents key extraction; FIPS 140-2 compliant
Legacy Device (no crypto support) None (upgrade or replace) None None Isolated VLAN with gateway encryption Cannot secure device itself; compensate with network-level encryption at gateway

Decision Tree:

  1. Does the device have AES hardware acceleration?
    • YES → Use AES-128-GCM for symmetric encryption
    • NO → Use ChaCha20-Poly1305 (faster in software than AES)
  2. Does the device have >64 KB RAM?
    • YES → Use ECC P-256 for asymmetric (supports TLS/DTLS)
    • NO → Use Ed25519 (smaller stack footprint than ECDSA)
  3. Does the device transmit sensitive regulated data (HIPAA, PCI-DSS)?
    • YES → Use AES-256-GCM + hardware secure element (ATECC608) for key storage
    • NO → AES-128-GCM is sufficient for commercial IoT
  4. What is the device operational lifespan?
    • <5 years → AES-128, RSA-2048, SHA-256 (current standards)
    • 5-10 years → AES-256, ECC P-384, SHA-384 (future-proofing)
    • 10+ years → Plan for post-quantum cryptography transition (CRYSTALS-Kyber, CRYSTALS-Dilithium)

Best Practice Summary:

  • Default choice: AES-128-GCM (symmetric) + ECC P-256 (asymmetric) + SHA-256 (hash)
  • Upgrade to AES-256 for: Medical devices, financial IoT, government deployments (FIPS compliance)
  • Use hardware crypto chips when: Device stores long-term keys, compliance required, or attack risk is high
Common Mistake: Using ECB Mode for IoT Sensor Data Encryption

What Developers Do Wrong: Many IoT projects use AES in ECB (Electronic Codebook) mode because it’s the simplest mode to implement — no initialization vector (IV) required, deterministic output, easy to parallelize. A developer encrypts temperature sensor readings with AES-128-ECB, sends ciphertext over MQTT, and assumes the data is secure.

Why It Fails Catastrophically: ECB mode encrypts each 16-byte block independently with the same key. Identical plaintext blocks always produce identical ciphertext blocks, revealing patterns even without decryption:

  • Temperature sensor sends: {"temp":22} → Ciphertext A
  • 10 minutes later, sends: {"temp":22}Same Ciphertext A
  • Attacker observes: “Ciphertext A repeated 50 times today = temperature hasn’t changed”
  • Even worse: Attacker can recognize “22°C” ciphertext vs “28°C” ciphertext without knowing the key, then replay the “22°C” ciphertext when AC should be off, tricking the HVAC controller

Real-World Example: In 2020, a smart thermostat manufacturer used AES-ECB for temperature setpoint commands. Security researchers captured encrypted “set to 16°C” commands and replayed them to chill buildings to 16°C during summer heatwaves. Despite AES-128 encryption, the system was completely broken.

Correct Approach: Always use authenticated encryption modes with randomized IVs: - AES-128-GCM (best for IoT): Provides encryption + authentication in one pass, prevents tampering - AES-128-CCM (alternative): Designed for resource-constrained devices, used in Zigbee/Thread - ChaCha20-Poly1305: Fast on devices without AES hardware acceleration

Implementation Fix (ESP32 example):

// WRONG: ECB mode (deterministic)
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext);

// CORRECT: GCM mode (random IV, authenticated)
unsigned char iv[12];
mbedtls_ctr_drbg_random(&ctr_drbg, iv, 12);  // Generate random IV
mbedtls_gcm_crypt_and_tag(&gcm, MBEDTLS_GCM_ENCRYPT, len, iv, 12,
                          NULL, 0, plaintext, ciphertext, 16, tag);
// Send: IV || ciphertext || tag

The Cost: Using ECB instead of GCM on a 100-device industrial IoT deployment allowed attackers to infer production schedules from traffic patterns and launch a ransomware attack targeting high-production periods. Loss: $2.3M in downtime. The 5-line code change to GCM would have prevented the entire attack.

Concept Relationships
Concept Related To Relationship Type
Symmetric Encryption AES-GCM, ChaCha20 Implements - Fast bulk data encryption using shared secret keys
Asymmetric Encryption RSA, ECC, Key Exchange Enables - Secure key distribution without pre-shared secrets
Hash Functions SHA-256, Integrity Checking Provides - One-way fingerprints for data verification
HMAC Message Authentication Combines - Hash + secret key for authenticated messages
Digital Signatures Public Key, Non-Repudiation Proves - Message origin and prevents sender denial
Key Management Secure Elements, TPM Protects - Cryptographic keys in tamper-resistant hardware
See Also

Foundation Concepts:

Related Security Topics:

Practical Applications:

Build an Elliptic Curve Diffie-Hellman key exchange to understand how devices establish shared secrets without pre-sharing.

Exercise Steps:

  1. Generate two key pairs (Alice and Bob) using P-256 curve
  2. Exchange public keys (transmitted in cleartext over insecure channel)
  3. Compute shared secret using your private key + their public key
  4. Verify both sides computed SAME shared secret
  5. Derive AES-128 key from shared secret using HKDF

Starter Code (Python with cryptography library):

from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

# Alice generates key pair
alice_private = ec.generate_private_key(ec.SECP256R1())
alice_public = alice_private.public_key()

# Bob generates key pair
bob_private = ec.generate_private_key(ec.SECP256R1())
bob_public = bob_private.public_key()

# Alice computes shared secret using Bob's public key
alice_shared = alice_private.exchange(ec.ECDH(), bob_public)

# Bob computes shared secret using Alice's public key
bob_shared = bob_private.exchange(ec.ECDH(), alice_public)

# Verify both computed same secret
assert alice_shared == bob_shared
print(f"Shared secret: {alice_shared.hex()[:32]}...")

# Derive AES key from shared secret
aes_key = HKDF(
    algorithm=hashes.SHA256(),
    length=16,  # 128-bit AES
    salt=None,
    info=b'IoT-session-key'
).derive(alice_shared)

print(f"AES-128 key: {aes_key.hex()}")

What to Observe:

  • Public keys transmitted in cleartext (eavesdropper sees them)
  • Private keys NEVER transmitted (stay on device)
  • Both sides compute SAME shared secret from different calculations
  • Eavesdropper cannot compute shared secret (discrete logarithm problem)
  • Shared secret → HKDF → session key for AES encryption

Extension: Implement full TLS-style handshake with server authentication using ECDSA signatures

RSA security relies on the computational difficulty of factoring the product of two large primes: \(N = p \times q\) where \(p, q\) are primes.

RSA Key Pair:

Public key: \((N, e)\) where \(e\) is public exponent (commonly 65537)

Private key: \((N, d)\) where \(d\) satisfies \(ed \equiv 1 \pmod{\phi(N)}\)

Working through an example:

Given: Generate RSA-2048 key pair (educational example with small primes).

Step 1: Select two primes \[p = 61, \quad q = 53\]

Step 2: Compute modulus \[N = p \times q = 61 \times 53 = 3233\]

Step 3: Compute Euler’s totient \[\phi(N) = (p-1)(q-1) = 60 \times 52 = 3120\]

Step 4: Choose public exponent \[e = 17 \quad (\text{coprime to } \phi(N))\]

Step 5: Compute private exponent (Extended Euclidean Algorithm) \[d = e^{-1} \bmod \phi(N) = 2753\]

Verify: \(ed \bmod \phi(N) = 17 \times 2753 \bmod 3120 = 1\)

Encryption: \(c = m^e \bmod N = 123^{17} \bmod 3233 = 855\)

Decryption: \(m = c^d \bmod N = 855^{2753} \bmod 3233 = 123\)

Security: Factoring \(N=3233\) is trivial (\(61 \times 53\)). Real RSA-2048 uses 1024-bit primes – factoring a 2048-bit modulus requires \(\approx 2^{112}\) operations using the best known algorithms (infeasible with current technology).

Result: RSA-2048 provides ~112-bit security. ECC P-256 provides ~128-bit security with 256-bit keys (8× smaller than RSA-2048). For IoT, ECC wins on efficiency.

In practice: RSA-2048 signatures require 2048-bit keys, 256-byte signatures, and slow verification (~10-50ms on ESP32). ECDSA P-256 uses 256-bit keys, 64-byte signatures, and fast verification (~5-10ms). For firmware signing on constrained devices, ECC’s smaller keys and faster operations reduce OTA update time and energy consumption.

Interactive RSA Explorer: Try different small primes to see how RSA key generation works.

4.9 Chapter Summary

Cryptography provides the technical foundation for IoT data protection. Symmetric encryption (AES) offers fast, efficient bulk data encryption suitable for resource-constrained devices. Asymmetric encryption (RSA, ECC) enables secure key exchange and digital signatures without pre-shared secrets. Hash functions provide data integrity verification, while HMAC adds authentication to ensure messages come from authorized senders.

Algorithm selection depends on device capabilities and security requirements: use AES-128 or ChaCha20 for data encryption, ECC (Ed25519 or ECDSA P-256) for signatures, and SHA-256 for hashing. Always use per-device keys rather than global keys to limit the blast radius of any single device compromise.

4.10 Knowledge Check

Common Pitfalls

Mistake: Assuming AES-128 encryption alone proves the sender is legitimate. Why it happens: Encryption ensures confidentiality, not identity. Fix: Always pair encryption with HMAC or digital signatures; use authenticated encryption modes like AES-GCM that provide both in one operation.

Mistake: Selecting AES-ECB for device data because it is simpler to implement. Why it happens: ECB requires no IV management, but identical plaintext blocks produce identical ciphertext, leaking patterns. Fix: Always use AES-CBC with a random IV, or preferably AES-GCM for authenticated encryption.

Mistake: Embedding symmetric keys directly in firmware or configuration files. Why it happens: Simplicity during development carries over to production. Fix: Use hardware security modules (HSM), Trusted Execution Environments (TEE), or secure element chips (ATECC608) to store keys outside readable memory.

Mistake: Using the same session key for months or years. Why it happens: Key rotation adds operational complexity. Fix: Implement automatic key rotation schedules — hourly for high-security applications, daily for standard IoT deployments — using derived keys from a master secret.

Mistake: Deploying RSA-2048 on microcontrollers with limited RAM and CPU. Why it happens: RSA is more familiar than ECC. Fix: Use Curve25519 or NIST P-256 ECC which provide equivalent security to RSA-3072 at 10x less computational cost, critical for battery-powered IoT devices.

4.11 What’s Next

With cryptographic fundamentals in place, the next chapter examines Authentication Methods where you’ll learn to implement password-based, certificate-based, and token-based authentication systems for IoT devices.

Direction Chapter Focus
Prerequisites Security Overview CIA triad and why confidentiality matters
Prerequisites Defense in Depth How encryption fits into layered security
Next Secure Comms & Firmware TLS/DTLS, VPN, and secure boot
Next Authentication Methods Certificate-based and token-based auth