13  Key Management for IoT Devices

13.1 Learning Objectives

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

  • Design Key Lifecycle: Plan key generation, distribution, storage, rotation, and destruction
  • Implement Secure Storage: Use hardware security modules, secure elements, and encrypted storage
  • Apply Key Derivation: Generate multiple keys from a single master secret using KDFs
  • Handle Provisioning: Securely inject keys during manufacturing or first-use enrollment
In 60 Seconds

IoT key management encompasses the full lifecycle of cryptographic keys — generation, distribution, storage, rotation, and revocation — ensuring that keys remain secure across millions of deployed devices.

Key management is about safely creating, distributing, storing, and retiring the encryption keys that protect IoT data. Think of it like managing the keys to a large building – you need to track who has which key, replace locks when a key is lost, and ensure former employees return their keys. Poor key management undermines even the strongest encryption.

“Having the world’s strongest lock is useless if you leave the key under the doormat!” Max the Microcontroller said firmly. “Key management is about the entire life of a cryptographic key – from birth to death.”

Sammy the Sensor walked through the lifecycle. “Step one: generation – create keys using a truly random number generator, not predictable patterns. Step two: distribution – get the key safely to the device, like during manufacturing or through a secure enrollment process. Step three: storage – keep the key in a hardware security module or secure element, never in plain text on the flash memory!”

“Step four is rotation,” Lila the LED continued. “Just like changing the locks on your house periodically, we change encryption keys regularly. If an old key somehow gets compromised, the damage is limited to data encrypted with that key. Step five is destruction – when a device is retired, the key must be completely erased so nobody can use it later.”

“The Mirai botnet proved that key management matters more than encryption strength,” Bella the Battery said. “Those devices had encryption capabilities but used hardcoded default passwords that anyone could look up online. The strongest vault in the world is worthless if the combination is ‘1234.’ Proper key management is the difference between theoretically secure and actually secure!”

In Plain English

Key management is about the lifecycle of cryptographic keys – from birth (generation) to death (destruction). Strong encryption with weak key management is like having an unbreakable safe with the combination written on a sticky note.

Why it matters for IoT: The 2016 Mirai botnet compromised hundreds of thousands of IoT devices – not by breaking encryption, but because devices had hardcoded default credentials. Key management is often the weakest link in IoT security.

13.2 The Key Lifecycle

Diagram showing the six stages of cryptographic key lifecycle: Generate (HSM/TRNG), Distribute (secure channel), Store (secure element/TPM), Use (encrypt/sign), Rotate (periodic renewal), and Destroy (secure erase/zeroization), connected by flow arrows
Figure 13.1: The six stages of cryptographic key lifecycle management

Every cryptographic key passes through six stages: generation, distribution, storage, use, rotation, and destruction. Failure at any stage compromises the entire system, regardless of how strong the other stages are.

13.3 1. Key Generation

13.3.1 Requirements

  • Sufficient entropy: Use hardware random number generators (TRNG), not PRNGs seeded with predictable values
  • Cryptographically secure: Keys must be indistinguishable from random
  • Appropriate length: Match key size to security requirements (e.g., 128-bit AES for symmetric, 256-bit for ECC)

13.3.2 IoT Key Generation Sources

Source Entropy Quality Use Case
Hardware TRNG Excellent Production keys
Noise-based RNG Good Session keys
Software PRNG Poor Never for crypto
Timestamps/MACs Terrible Never use

13.3.3 Platform-Specific TRNG

// ESP32
uint32_t random_value = esp_random();

// STM32
HAL_RNG_GenerateRandomNumber(&hrng, &random_value);

// nRF52
nrf_drv_rng_rand(&random_buffer, size);

13.4 Never Generate Keys From Predictable Values

WRONG:

// MAC addresses have limited entropy (~2^24 variable bits per OUI)
key = SHA256(device_mac_address);

// Serial numbers are sequential
key = SHA256(serial_number);

// Timestamps are predictable
key = SHA256(time(NULL));

RIGHT:

// Use hardware TRNG
uint8_t key[32];
esp_fill_random(key, sizeof(key));
Try It: Entropy Source Strength Explorer

Compare different entropy sources and see how their predictability affects key security. Adjust the source type and key length to understand why hardware TRNGs are essential for cryptographic key generation.

13.5 2. Key Distribution

13.5.1 Manufacturing Provisioning

Diagram illustrating the four steps of secure key provisioning during manufacturing: factory HSM generates unique keys, keys are injected into secure element, certificate is bound to device ID, and audit trail is recorded
Figure 13.2: Secure key injection during manufacturing showing factory HSM key generation, injection into secure element, certificate binding, and audit trail

13.5.2 Provisioning Methods

Method Security Complexity Use Case
Factory injection Highest High Mass production
First-use enrollment High Medium Consumer devices
QR code + secure channel Medium Low Onboarding
Hardcoded defaults None None Never use

13.5.3 Certificate-Based Provisioning

For large deployments, use X.509 certificates:

  1. Device generates keypair locally (private key never leaves device)
  2. Device sends CSR (Certificate Signing Request) to CA
  3. CA signs certificate and returns to device
  4. Device stores certificate for future authentication

13.6 3. Key Storage

13.6.1 Storage Options (Ranked by Security)

Storage Type Security Cost Use Case
Secure Element (e.g., ATECC608B) Highest \[$ | High-value devices | | **TPM** | Very High | \] Industrial IoT
Hardware key storage High $$ Automotive, medical
Encrypted NVS (e.g., ESP32) High $ Consumer IoT
Plain flash None - Never use

13.6.2 Secure Element Integration

// ATECC608B example - key never leaves chip
atca_aes_encrypt(key_id, plaintext, ciphertext);

// Private key operations in secure element
atca_sign(SIGN_KEY_ID, digest, signature);

13.6.3 Encrypted Flash Storage

For devices without secure elements:

// ESP32 NVS encryption
nvs_open("keys", NVS_READWRITE, &handle);
// Keys encrypted with flash encryption key
// Derived from eFuse-protected master key
Key Storage Anti-Patterns

Never do:

// Hardcoded in source code
const char* API_KEY = "sk_live_abc123...";

// Plain text config file
echo "secret_key=abc123" > /etc/config.ini

// Environment variables visible in logs
export SECRET_KEY="abc123"

Always:

  • Use hardware secure storage when available
  • Encrypt keys at rest with device-unique key
  • Derive runtime keys, don’t store them permanently

13.7 4. Key Derivation

Use Key Derivation Functions (KDFs) to generate multiple purpose-specific keys from a single master secret.

13.7.1 HKDF (HMAC-based Key Derivation Function)

HKDF operates in two phases: Extract compresses the input keying material into a fixed-length pseudorandom key (PRK), and Expand derives one or more output keys from the PRK using context-specific info strings.

13.7.2 Benefits of Key Derivation

  1. Single provisioning: Inject one master key, derive others as needed
  2. Key separation: Compromise of one derived key doesn’t expose others
  3. Unlimited keys: Generate session keys, per-message keys, etc.
  4. Reproducible: Same inputs always produce same outputs (deterministic)

13.7.3 Example: Deriving Session Keys

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

master_key = b"device_master_secret_32_bytes..."
session_id = b"session_20240115_143052"

# Derive unique session key
hkdf = HKDF(
    algorithm=hashes.SHA256(),
    length=32,
    salt=None,
    info=b"session_encryption_" + session_id
)
session_key = hkdf.derive(master_key)

Objective: Derive multiple purpose-specific keys from a single master secret, demonstrating how one provisioned key can generate unlimited session keys.

from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
import os

# Simulate a master key provisioned during manufacturing
master_key = os.urandom(32)
print(f"Master key: {master_key.hex()[:32]}...")

def derive_key(master, purpose, session_id):
    """Derive a purpose-specific key from master secret"""
    info = f"{purpose}:{session_id}".encode()
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=info
    )
    return hkdf.derive(master)

# Derive different keys for different purposes
encryption_key = derive_key(master_key, "encryption", "session_001")
signing_key = derive_key(master_key, "signing", "session_001")
auth_key = derive_key(master_key, "auth", "session_001")

print(f"\nEncryption key: {encryption_key.hex()[:32]}...")
print(f"Signing key:    {signing_key.hex()[:32]}...")
print(f"Auth key:       {auth_key.hex()[:32]}...")

# All keys are different even from the same master
print(f"\nAll keys unique: {len({encryption_key, signing_key, auth_key}) == 3}")

# Same inputs always produce the same key (deterministic)
encryption_key_2 = derive_key(master_key, "encryption", "session_001")
print(f"Reproducible:   {encryption_key == encryption_key_2}")

# Different session = different keys (forward secrecy)
next_session_key = derive_key(master_key, "encryption", "session_002")
print(f"Session isolation: {encryption_key != next_session_key}")

What to Observe:

  1. One master key generates unlimited derived keys for different purposes
  2. Each derived key is cryptographically independent – compromising one does not reveal others
  3. The derivation is deterministic – both sides independently compute the same keys
  4. Different sessions produce different keys, limiting the blast radius of compromise

13.8 5. Key Rotation

13.8.1 Why Rotate Keys?

  • Limit exposure: If a key is compromised, limit the damage window to the current rotation period
  • Cryptoperiod compliance: NIST SP 800-57 recommends maximum cryptoperiods (e.g., 2 years for symmetric encryption keys)
  • Regulatory requirements: Many standards (PCI DSS, HIPAA) require periodic rotation

13.8.2 Rotation Strategies

Strategy Frequency Trigger Use Case
Time-based Daily/monthly Timer Session keys
Usage-based After N uses Counter Encryption keys
Event-based On compromise Detection All keys
Hybrid Whichever first Both Best practice

13.8.3 Automated Rotation Example

from datetime import datetime, timedelta

# Check if key needs rotation
key_created = get_key_creation_time()
key_age = datetime.now() - key_created
max_age = timedelta(days=30)

if key_age > max_age:
    # Generate new key
    new_key = generate_key()

    # Re-encrypt data with new key (gradual migration)
    migrate_encrypted_data(old_key, new_key)

    # Destroy old key after migration
    secure_delete(old_key)
Try It: Key Rotation Exposure Calculator

Model how rotation frequency limits the blast radius of a key compromise. Adjust the rotation period and breach timing to see how much data is at risk versus a never-rotated key.

13.9 6. Key Destruction

13.9.1 Secure Deletion Requirements

  1. Overwrite memory: Don’t just free() – overwrite with zeros first
  2. Handle flash wear-leveling: Flash storage may retain old data in spare blocks (see warning below)
  3. Verify destruction: Confirm data is unrecoverable
  4. Audit trail: Log destruction events (but never log the key itself)

13.9.2 Platform-Specific Secure Deletion

// Secure key zeroization
void secure_zero(void* ptr, size_t len) {
    volatile unsigned char* p = ptr;
    while (len--) *p++ = 0;
}

// ESP32: Erase NVS key
nvs_erase_key(handle, "device_key");
nvs_commit(handle);
Flash Storage Challenge

Flash memory uses wear-leveling, which may leave copies of old data in spare blocks even after overwriting. For high-security applications:

  1. Never store unencrypted keys in flash – always encrypt before writing
  2. Store keys only in secure elements where possible
  3. Use full-disk encryption with a hardware-protected master key
  4. If flash storage is unavoidable, derive keys at runtime from a hardware-protected secret rather than storing them persistently

13.10 Key Management Architecture

Layered architecture diagram showing four tiers of key hierarchy: master key protected in HSM at the top, device keys derived from master in the second tier, ephemeral session keys in the third tier, and per-service application keys at the bottom
Figure 13.3: Hierarchical key architecture showing master key protected in HSM, with derived device keys, session keys, and application keys
Try It: Key Hierarchy Explorer

Explore how a hierarchical key architecture scales. Adjust the number of devices, sessions per device, and services to see the total number of derived keys and understand why key derivation (HKDF) is essential for fleet management.

13.11 Worked Example: Secure Key Storage Cost-Benefit Analysis

Scenario: A manufacturer deploys 100,000 smart home sensors. Compare the cost and security of three key storage approaches over a 5-year product lifecycle.

Factor Plain Flash Encrypted NVS (ESP32) Secure Element (ATECC608B)
Unit cost (component) $0.00 $0.00 (built-in) $0.50–0.80
Fleet cost (100K units) $0 $0 $50,000–80,000
Key extraction difficulty Minutes (JTAG dump) Hours (side-channel attack) Infeasible (tamper-resistant)
Firmware update to rotate keys Yes (risky) Yes (moderate) No (hardware handles it)
FIPS 140-2 certifiable No No Yes (Level 2+)
Recovery from single breach Recall all devices OTA key rotation Revoke one device certificate

Decision: At typical costs of $0.50–0.80 per unit, secure elements represent roughly 1–2% of device retail price but provide significant ROI against breach events. For devices handling personal data, health data, or physical access (locks, cameras), secure elements are strongly recommended.

What happened: Attackers gained access to 150,000 security cameras across hospitals, prisons, schools, and Tesla factories through a single “super admin” credential hardcoded in the system.

Key management failures:

Failure Impact Correct Approach
Shared admin credential One credential = access to ALL cameras Per-device unique certificates
Credentials in cloud database Single database breach = fleet compromise Hardware-bound keys in secure elements
No key rotation Credential valid indefinitely Automated rotation (e.g., 90-day policy)
No privilege separation “Super admin” could access every camera Role-based access with per-facility keys

Quantified damage:

  • 150,000 cameras compromised across 3 days
  • Patient privacy violations (HIPAA) in hospitals
  • Prison surveillance footage exposed
  • Tesla manufacturing footage leaked
  • Significant legal settlements and security remediation costs
  • Company valuation dropped substantially

Lesson: Verkada had strong encryption on the video streams. The encryption was irrelevant because the key management was catastrophically flawed. A secure element per camera with unique device certificates would have limited the breach to a single camera instead of 150,000.

Concept Relationships
Concept Depends On Enables Security Impact
Key Generation Hardware TRNG Unpredictable keys Weak RNG = predictable keys
Key Provisioning Secure manufacturing process Fleet deployment Hardcoded keys = fleet compromise
Secure Storage Hardware security modules Tamper resistance Plain flash = key extraction via JTAG
Key Derivation (KDF) Master key + HKDF Multiple keys from one secret Single provisioning, unlimited keys
Key Rotation Automated renewal system Limited breach window Static keys = permanent compromise
Key Destruction Secure erasure Prevent key recovery Simple delete = forensic recovery
Key Hierarchy Master, Intermediate, Session Granular revocation Flat hierarchy = binary trust

Critical Path: Generate (TRNG) -> Provision (factory) -> Store (secure element) -> Derive (KDF) -> Rotate (automated) -> Destroy (overwrite). Breaking any step compromises the overall security posture.

13.12 Best Practices Summary

  1. Generate keys from hardware TRNG – Never from predictable values
  2. Provision keys securely – Factory injection or first-use enrollment
  3. Store keys in secure elements – Or encrypted with device-unique key
  4. Use key derivation – One master key derives all others via HKDF
  5. Rotate keys regularly – Limit exposure from potential compromise
  6. Destroy keys securely – Overwrite, don’t just delete
  7. Audit key operations – Log access, rotation, destruction
  8. Plan for compromise – Have revocation and recovery procedures ready

HKDF (HMAC-based Key Derivation Function, defined in RFC 5869) expands a single master key into multiple cryptographically independent derived keys.

\[\text{HKDF}(salt, IKM, info, L) = \text{Expand}(\text{Extract}(salt, IKM), info, L)\]

where \(IKM\) is input keying material, \(info\) is a context string, and \(L\) is the desired output length in bytes.

Working through an example:

Given: 32-byte master key provisioned during manufacturing, derive 3 session keys for encryption, signing, and authentication.

Step 1: Extract phase (create pseudorandom key) \[PRK = \text{HMAC-SHA256}(salt, IKM)\]

  • \(IKM\): 32-byte master key
  • \(salt\): 16-byte random value (or all-zero if no salt available)
  • \(PRK\): 32-byte pseudorandom key

Step 2: Expand phase (derive multiple keys) \[K_1 = \text{HMAC-SHA256}(PRK, info_1 \,||\, 0x01)\] \[K_2 = \text{HMAC-SHA256}(PRK, K_1 \,||\, info_2 \,||\, 0x02)\] \[K_3 = \text{HMAC-SHA256}(PRK, K_2 \,||\, info_3 \,||\, 0x03)\]

Step 3: Apply to IoT scenario - \(info_1\) = “session_encryption_key” - \(info_2\) = “session_signing_key” - \(info_3\) = “session_auth_key”

Result: One 32-byte master key generates unlimited derived keys. Compromising \(K_1\) (encryption key) does not expose \(K_2\) (signing) or \(K_3\) (auth) due to HMAC’s one-way property.

In practice: Provision one master key per device during manufacturing. Derive session-specific keys at runtime using HKDF. No need to store derived keys – regenerate deterministically on each boot. This limits flash wear and reduces the key extraction attack surface.

13.13 Knowledge Check

A developer generates encryption keys using SHA256(device_serial_number). What is the security problem?

Options:

    1. SHA-256 is too slow for key generation
    1. Serial numbers are sequential/predictable, allowing attackers to pre-compute all possible keys
    1. SHA-256 output is too short for encryption keys
    1. This approach uses too much battery

Correct: B

Serial numbers are sequential and predictable. An attacker can enumerate all possible serial numbers and pre-compute the corresponding keys. For example, if serial numbers are 8-digit numbers (00000001–99999999), there are only 100 million possible keys – trivially computable. Keys must be generated from high-entropy sources like hardware TRNGs.

Your IoT device stores an AES encryption key in flash memory at a known address. What is the primary security concern?

Options:

    1. Flash memory is too slow for encryption operations
    1. An attacker with physical access can extract the key using JTAG/SWD or flash dumping
    1. AES keys are too large for flash storage
    1. Flash memory corrupts keys over time

Correct: B

Plain-text keys in flash can be extracted via physical attacks (JTAG debugging, flash chip removal, logic analyzer). Solutions include: secure elements that never expose keys, encrypted flash with eFuse-protected master key, or secure boot that validates firmware before releasing keys.

Key Concepts

  • Key Lifecycle: The stages a cryptographic key goes through: generation → distribution → use → rotation → revocation → destruction.
  • Key Derivation Function (KDF): An algorithm that derives one or more cryptographic keys from a master secret or password (e.g., HKDF, PBKDF2), allowing unique per-device keys from a single root.
  • Key Rotation: The practice of periodically replacing cryptographic keys to limit the amount of data encrypted under a single key and reduce exposure from key compromise.
  • Hardware Security Module (HSM): A tamper-resistant hardware device that generates, stores, and manages cryptographic keys; root keys never leave the HSM in plaintext.
  • Secure Element: A tamper-resistant chip embedded in IoT devices (or SIM cards) that stores keys and performs cryptographic operations without exposing keys to the main processor.
  • Certificate Revocation: The process of invalidating a certificate before its expiry (e.g., when a device is compromised or decommissioned), using CRL or OCSP.
  • Key Escrow: Storing a copy of encryption keys with a trusted third party to allow recovery in case the primary key holder loses access.

Place the secure key provisioning steps in the correct order:

Common Pitfalls

Using the same encryption key indefinitely means that a single key compromise exposes all historical and future data. Define key rotation schedules based on data sensitivity and implement automated rotation in your key management system.

Storing a device’s encryption key in the same memory region as the data it protects eliminates all security value — an attacker accessing the data also gets the key. Keep keys in a separate, protected partition or hardware secure element.

Sending a shared secret over an unencrypted connection (plaintext HTTP, MQTT without TLS) exposes it to any network observer. Use asymmetric key exchange (ECDH, RSA) or a pre-established secure channel for all key distribution.

Devices that leave the field (sold, discarded, stolen) retain their keys unless revoked. Maintain a device registry and immediately revoke certificates/keys when a device is decommissioned.

13.14 Summary

  • Key management is often the weakest link – Strong encryption means nothing with poor key handling
  • Generate keys from true randomness – Hardware TRNGs, never predictable values
  • Store keys securely – Secure elements > encrypted flash > never plain text
  • Use key derivation – HKDF generates multiple keys from one master secret
  • Rotate keys regularly – Limit the window of exposure if compromised
  • Destroy keys securely – Overwrite memory, don’t just delete references

13.15 See Also

Prerequisites:

Implementation:

Advanced Topics:

Standards:

13.16 What’s Next

If you want to… Read this
Understand key renewal and the E5 tier Key Renewal & E5 Architecture
Learn how asymmetric crypto enables key exchange Asymmetric Encryption
Explore TLS certificate management TLS and DTLS for IoT
See the complete encryption architecture Encryption Architecture & Levels

Continue to Interactive Encryption Tools to explore calculators and simulators that help you understand encryption strength, compare algorithms, and make informed security decisions.