ESP32 Bluetooth Security: Secure Pairing and Encryption

Bluetooth security is non-negotiable in IoT. For ESP32 developersHybrid Cloud/Edge Architectures: ESP32 with AWS GreengrassHybrid Cloud/Edge Architectures: ESP32 with AWS GreengrassDiscover our comprehensive guide to integrating ESP32 with AWS Greengrass. Master hybrid cloud/edge solutions, security and practical IoT applications., vulnerabilities like eavesdropping, man-in-the-middle (MITM) attacks, or unauthorized device access can compromise entire systems. This article dives into secure pairing, encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies., and key management for Bluetooth Classic and BLEArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. on the ESP32, blending theoretical depth with actionable code examples.

Table of Contents🔗

Secure Pairing Methods🔗

Bluetooth pairing establishes a trusted relationship between devices. The ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. supports three methods:

Legacy Pairing (Bluetooth Classic)

Uses a fixed PIN (e.g., "1234") vulnerable to brute-force attacks. Avoid for sensitive applications.

// Example: Set legacy PIN for Bluetooth Classic
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_FIXED;
esp_bt_pin_code_t pin_code;
strcpy((char *)pin_code, "1234");
esp_bt_gap_set_pin(pin_type, 4, pin_code);

Secure Simple Pairing (SSP)

Uses elliptic-curve Diffie-Hellman (ECDH) for key exchange. Preferred for Classic and BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLEExplore ESP32 connectivity with Wi-Fi, Bluetooth Classic, and BLE. Learn implementation tips and best practices for IoT projects..

Modes:

  • Numeric Comparison: User verifies a 6-digit code on both devices.
  • Passkey Entry: User inputs a 6-digit code on one device.
  • Just Works: No user interaction (less secure).

LE Secure Connections (BLE 4.2+)

Upgrades SSP with stronger AES-128 encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. and elliptic-curve cryptography (ECC).

MethodSecurity LevelUse Case
Legacy PairingLowLegacy devices
Just WorksMediumNon-critical data
Numeric ComparisonHighUser-verified actions
Passkey EntryHighAuthentication required
// Enable LE Secure Connections on ESP32
esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;
esp_ble_io_cap_t iocap = ESP_IO_CAP_KBDISP;  // Device can display a passkey
esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));

Encryption in Bluetooth Classic and BLE🔗

EncryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. ensures data confidentiality. The ESP32 uses AESNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security.-128-CCM for BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLEExplore ESP32 connectivity with Wi-Fi, Bluetooth Classic, and BLE. Learn implementation tips and best practices for IoT projects. and AESNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security.-128 for Classic.

Key Generation

// Enable encryption for a BLE connection
esp_ble_set_encryption(param->connect.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM);

Mitigating MITM Attacks🔗

MITM attacks intercept or alter communication. Defenses include:

  • Numeric Comparison/Passkey Entry: Requires user verification.
  • Secure Connections Only: Disable Legacy Pairing.
// Force LE Secure Connections (disable Legacy)
esp_ble_sec_t sec_param;
sec_param.sec_conn = true;
esp_ble_gap_set_security_param(ESP_BLE_SEC_ACT, &sec_param, sizeof(sec_param));

Bonding and Key Management🔗

Bonding stores keys for reconnectionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. without repairing.

Storing Keys on ESP32

Use Non-Volatile Storage (NVS) to save LTKs securely:

// Save LTK to NVS
nvs_handle_t handle;
nvs_open("storage", NVS_READWRITE, &handle);
nvs_set_blob(handle, "ltk", ltk, 16);
nvs_commit(handle);

Common Vulnerabilities and Mitigations🔗

VulnerabilityMitigation
Weak PINsUse 6+ digit passkeys
No MITM ProtectionEnable ESP_LE_AUTH_REQ_SC_MITM_BOND
Key ReuseRotate LTKs periodically

Testing Security with ESP32🔗

Use tools like Wireshark (with Ubertooth) or nRF Connect to sniff packets.

// Test secure BLE characteristic read
esp_ble_gattc_read_char(conn_id, srvc_id, char_id, ESP_GATT_AUTH_REQ_MITM);

Practical Example: Secure Smart Lock🔗

Scenario: A BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLEExplore ESP32 connectivity with Wi-Fi, Bluetooth Classic, and BLE. Learn implementation tips and best practices for IoT projects. smart lock using Passkey Entry.

1. Pairing:

esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;
esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, 1);

2. EncryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies.:

esp_ble_set_encryption(remote_bda, ESP_BLE_SEC_ENCRYPT_MITM);

3. Bonding:

Store LTK in NVS and validate on unlock.

Implementing LE Secure Connections🔗

LE Secure Connections is a feature introduced in Bluetooth 4.2Arquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. that enhances security by using Elliptic Curve Diffie-Hellman (ECDH) for key exchange. This method provides stronger encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. and better resistance to MITM attacks.

To implement LE Secure Connections on the ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips.:

1. Enable Secure Connections Only Mode in the ESP32’sCombining Wi-Fi with Deep Sleep for Low-Power ApplicationsCombining Wi-Fi with Deep Sleep for Low-Power ApplicationsLearn how to integrate Wi-Fi and deep sleep on ESP32 to maximize battery life in IoT devices. This guide offers practical tips and step-by-step instructions. Bluetooth stack.

2. Configure the pairing method (e.g., Numeric Comparison or Passkey Entry).

3. Use the esp_ble_gap_set_security_param() function to set security parameters.

esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; // Require Secure Connections, MITM protection, and bonding
esp_ble_io_cap_t iocap = ESP_IO_CAP_OUT; // Set I/O capabilities (e.g., display only)
esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ, &auth_req, sizeof(auth_req));
esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(iocap));

Practical Example: Secure BLE Communication with ESP32🔗

Let’s walk through an example of implementing secure BLE communicationSetting Up BLE Client Communication on ESP32Setting Up BLE Client Communication on ESP32Learn how to configure the ESP32 as a BLE client. This guide explains scanning, connecting, and interacting with a variety of IoT devices effortlessly. on the ESP32:

1. Set Up the GATTNative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLENative Protocols: Wi-Fi (2.4 GHz), Bluetooth Classic, and BLEExplore ESP32 connectivity with Wi-Fi, Bluetooth Classic, and BLE. Learn implementation tips and best practices for IoT projects. Server:

2. Pairing Process:

  • Use Numeric Comparison or Passkey Entry for secure pairing.
  • Store bonding keys for future connections.

3. Encrypt Data:

// Example: Setting up a secure GATT server
esp_ble_gatts_create_service(gatts_if, &service_id, NUM_HANDLE);
esp_ble_gatts_add_char(service_handle, &char_uuid, ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED, ...);

Best Practices and Challenges🔗

Successfully implementing secure Bluetooth pairing and encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. involves more than just the code:

  • Test Different Pairing Modes:

Evaluate how each pairing method behaves in real-world scenarios, including when devices are in constrained environments or suffer from interferenceZigbee Network Diagnostics: Resolving Packet Loss and InterferenceZigbee Network Diagnostics: Resolving Packet Loss and InterferenceDiscover effective methods to diagnose and resolve packet loss and interference in Zigbee networks using ESP32, ensuring reliable IoT connectivity..

  • Monitor and Log:

Implement robust logging during pairing and bonding to troubleshoot anomalies or potential handshake failures.

  • Mitigate MITM Attacks:

If your device is at risk, consider implementing out-of-band (OOB) pairing using a secondary secure channel (like NFCNFC Security: Implementing Encryption and Tamper DetectionNFC Security: Implementing Encryption and Tamper DetectionLearn how to secure your ESP32 NFC projects with AES encryption, HMAC validation, and tamper detection techniques for robust wireless security.) to further safeguard the key exchange process.

  • Regularly Update Firmware:

Security vulnerabilities evolve, so ensure that your ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. firmware is regularly updated to incorporate the latest patches for the Bluetooth stack.

  • User Education:

For devices requiring user interaction, provide clear feedback during the pairing process to assist users in verifying the authenticity of the connection.

Conclusion🔗

Bluetooth security on ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. hinges on strong pairing methods, encryptionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies., and rigorous key management. By enforcing LE Secure Connections, bonding keys, and MITM protection, developers can build resilient IoTSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. systems. Always validate with real-world testing tools.

Securing Bluetooth connections on the ESP32 is a blend of deep theoretical insight and practical implementation. By carefully selecting pairing methods, enforcing encryption through robust key exchanges, and following industry best practicesZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications., you can protect your IoT devices from potential security threats. Whether you’re developing industrial applications or innovative consumer products, mastering these techniques is vital for building reliable and secure IoT systems.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles