IoT · Embedded Systems
ESP32 BLE Passkey Pairing, Bonding, and Encryption
The default ESP32 BLE server accepts any connection. Build a secure peripheral with passkey pairing, MITM protection, and bonding using the Arduino BLE stack.
- Published
- Reading
- 7 min
- Author
- Fidelis Uwem Joseph
Series · Part 3 of 4BLE & AtomBrick
- AtomBrick: ESP32 BLE Motor Controller to KMP Mobile App
- BLE GATT Profile Design for Hardware Control: AtomBrick
- ESP32 BLE Passkey Pairing, Bonding, and Encryption
- Kotlin Multiplatform BLE with Kable, Koin, and Compose
The default ESP32 BLE example from Espressif ships with zero authentication. Any device in range can connect, read, and write your characteristics. For a product controlling physical actuators, that is not acceptable. This post shows how to add passkey pairing, MITM protection, and bonding to an ESP32 BLE server using the Arduino BLE stack, drawn from a real motor controller firmware.
Prerequisites
- ESP32 dev board with the Arduino framework via PlatformIO or Arduino IDE
- A working BLE server with at least one service and characteristic. Understand
BLEDevice,BLEServer,BLEService, andBLECharacteristicbefore continuing. - nRF Connect (iOS or Android) for verifying pairing behavior
Background
BLE security covers three independent concerns: encryption, authentication, and bonding. Most tutorials address none of them. The naive BLE server is discoverable, connectable, and writable by any peer in range, including other apps on a connected phone.
The ESP32 Arduino BLE library exposes BLEDevice::setEncryptionLevel and BLESecurity to configure all three. The interaction between SecurityCallbacks, BLEServerCallbacks, and the underlying esp_ble_* API is not documented in one place, and the callback firing order matters.
Implementation
1. Set the encryption level before init
These calls must happen before BLEDevice::init. Changes after init have no effect.
#define PASSKEY 123456
void setup() { BLEDevice::init("ATOMBRICK_SERVER"); BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT); BLEDevice::setSecurityCallbacks(new SecurityCallbacks());}2. Implement SecurityCallbacks
All five methods matter. Which ones fire depends on the IO capability configured in step 3.
class SecurityCallbacks : public BLESecurityCallbacks { uint32_t onPassKeyRequest() override { return PASSKEY; // Sent to the peer during pairing }
void onPassKeyNotify(uint32_t passkey) override { Serial.printf("Pairing PIN: %06d\n", passkey); }
bool onConfirmPIN(uint32_t passkey) override { return passkey == PASSKEY; // Numeric comparison pairing }
bool onSecurityRequest() override { return true; }
void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) override { authenticated = cmpl.success; Serial.printf("Auth %s\n", authenticated ? "OK" : "FAILED"); }};onPassKeyRequest fires when this device generates the passkey. onConfirmPIN handles numeric comparison pairing, where both sides display the same number. Which path is taken depends on ESP_IO_CAP_OUT vs ESP_IO_CAP_IO in step 3.
3. Configure BLESecurity with consistent flags
This is where most implementations fail silently: the auth mode, IO capability, and PIN method must be consistent with each other.
BLESecurity *pSecurity = new BLESecurity();pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND | ESP_LE_AUTH_REQ_MITM);pSecurity->setCapability(ESP_IO_CAP_OUT);pSecurity->setStaticPIN(PASSKEY);pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);ESP_LE_AUTH_BOND persists the link key. ESP_LE_AUTH_REQ_MITM requires man-in-the-middle protection, which forces passkey entry rather than “just works” pairing. ESP_IO_CAP_OUT declares that the device can display a passkey but cannot accept input, so the peer must enter it.
4. Resume advertising on disconnect
The ESP32 stops advertising after the first connection and does not resume automatically.
class ConnectionServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer *pServer) override { deviceConnected = true; authenticated = true; }
void onDisconnect(BLEServer *pServer) override { deviceConnected = false; pServer->getAdvertising()->start(); }};5. Gate characteristic writes on authentication
The characteristic callbacks can fire before authentication completes in edge cases. Guard every sensitive handler explicitly.
class MotorOneCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) override { if (!authenticated) return;
std::string value = pCharacteristic->getValue(); if (!value.empty()) { uint8_t command = value[0]; int8_t data = static_cast<int8_t>(value[1]); processMotorCommand(motorA, command, data); pCharacteristic->notify(); } }};The authenticated flag is set by onAuthenticationComplete. Without this guard, a peer that connects but fails pairing can still write characteristics before the ESP32 closes the connection.
6. Persist the device name across power cycles
Changing the advertised name at runtime requires re-initialising the BLE stack. Preferences (backed by ESP32 NVS flash) keeps the name across reboots.
class DeviceNameCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) override { std::string newName = pCharacteristic->getValue(); if (!newName.empty()) { BLEDevice::deinit(); delay(100); BLEDevice::init(newName.c_str()); preferences.putString("name", newName.c_str()); pServer->getAdvertising()->start(); } }};deinit tears down the stack cleanly. init brings it back with the new name. The previously configured security settings survive the cycle.
In setup, restore the stored name before BLEDevice::init:
preferences.begin("bt-config", false);String storedName = preferences.getString("name", DEVICE_NAME);BLEDevice::init(storedName.c_str());Testing and Verification
Flash the firmware and verify with nRF Connect:
- The device appears in the scan list under your advertised name.
- Tapping Connect triggers a pairing dialog. The phone requests the PIN.
- Enter
123456. The connection establishes. - Disconnect and reconnect. No PIN prompt appears (bonding worked).
- A second phone must re-pair from scratch.
[Serial Monitor]Starting Secure BLE Server...BLE Server Ready. Pairing PIN: 123456Device ConnectedAuth OKIf you see Auth FAILED immediately after connect, the IO capability and auth mode flags are inconsistent. Also check whether the phone has a cached bond from a previous insecure pairing. Clear the bond on both sides and try again.
Pitfalls
Production Considerations
A static PIN is sufficient for development. In a shipped product, derive the PIN from the device serial number and print it on the label. This gives each unit a unique PIN without adding a display to the hardware.
Per-characteristic access control via setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED) rejects reads and writes at the GATT layer unless the link is encrypted, adding a second layer of defence independent of the authenticated flag.
Going deeper
Fix the authentication flag lifecycle
Look again at ConnectionServerCallbacks in step 4: onConnect sets authenticated = true. That line quietly defeats the guard in step 5, because any peer that connects is treated as authenticated before pairing has even started. The flag should only ever be set by a successful pairing, and it must be cleared whenever a link starts or ends.
class ConnectionServerCallbacks : public BLEServerCallbacks { void onConnect(BLEServer *pServer) override { deviceConnected = true; authenticated = false; // pairing has not happened yet } void onDisconnect(BLEServer *pServer) override { deviceConnected = false; authenticated = false; pServer->getAdvertising()->start(); }};
// in SecurityCallbacksvoid onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) override { authenticated = cmpl.success; if (!cmpl.success) { Serial.printf("Auth failed (reason 0x%x), dropping link\n", cmpl.fail_reason); esp_ble_gap_disconnect(cmpl.bd_addr); }}Disconnecting a peer that fails pairing matters as much as the flag. Without it, the failed peer stays connected, occupies the only connection slot and keeps the device invisible to everyone else, because the ESP32 stops advertising while connected.
Enforce encryption in the GATT table
The authenticated flag is application code, and application code has bugs, as the previous section shows. GATT permissions move the check into the Bluetooth stack: a read or write on an unencrypted or unauthenticated link is rejected before your callback runs.
BLECharacteristic *motorOne = pService->createCharacteristic( MOTOR_ONE_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY);
// require an encrypted link established with MITM protection (passkey)motorOne->setAccessPermissions(ESP_GATT_PERM_READ_ENC_MITM | ESP_GATT_PERM_WRITE_ENC_MITM);
BLE2902 *cccd = new BLE2902();// subscribing to notifications is a write to this descriptor, so protect it toocccd->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);motorOne->addDescriptor(cccd);_ENC_MITM is stricter than _ENCRYPTED: a “just works” link is encrypted but not MITM-protected, so it fails the check. That also catches the IO capability downgrade described in the pitfalls, because the downgraded link cannot write anything.
When a phone hits a protected characteristic on an unpaired link, the stack answers with an “insufficient authentication” error. Android and iOS both react by starting pairing automatically, which is exactly the flow you want. Keep the authenticated check in onWrite as a second layer.
One PIN per device
A static 123456 shared by every unit means anyone who owns one device can pair with all of them. Deriving the PIN from the chip’s factory MAC address gives each unit its own PIN with no extra hardware:
#include <esp_mac.h>
uint32_t devicePasskey() { uint8_t mac[6]; esp_efuse_mac_get_default(mac);
// FNV-1a over the MAC plus a product salt uint32_t hash = 2166136261u; const char *salt = "atombrick-v1"; for (int i = 0; i < 6; i++) { hash ^= mac[i]; hash *= 16777619u; } for (const char *c = salt; *c; c++) { hash ^= *c; hash *= 16777619u; }
return hash % 1000000; // six digits, print with %06u}Run the same function once at the factory, print the result on the device label, and pass it to setStaticPIN(devicePasskey()) at boot. The salt is not a secret: anyone who dumps the firmware can read it. The goal is that PINs differ between units, not that they cannot be computed. If you need real secrecy, generate a random PIN at provisioning and store it in an encrypted NVS partition.
Manage bonds on the device
Bonds are stored in NVS and survive reboots and re-flashing unless the flash is erased. The default limit is 15 bonded peers (CONFIG_BT_SMP_MAX_BONDS). Two operations are worth exposing: listing bonds for debugging, and clearing them as part of a factory reset.
void printBonds() { int count = esp_ble_get_bond_device_num(); esp_ble_bond_dev_t *list = (esp_ble_bond_dev_t *) malloc(sizeof(esp_ble_bond_dev_t) * count); esp_ble_get_bond_device_list(&count, list); for (int i = 0; i < count; i++) { esp_bd_addr_t &a = list[i].bd_addr; Serial.printf("Bond %d: %02x:%02x:%02x:%02x:%02x:%02x\n", i, a[0], a[1], a[2], a[3], a[4], a[5]); } free(list);}
void clearBonds() { int count = esp_ble_get_bond_device_num(); esp_ble_bond_dev_t *list = (esp_ble_bond_dev_t *) malloc(sizeof(esp_ble_bond_dev_t) * count); esp_ble_get_bond_device_list(&count, list); for (int i = 0; i < count; i++) esp_ble_remove_bond_device(list[i].bd_addr); free(list);}A common pattern is to hold the BOOT button (GPIO 0 on most dev boards) for three seconds during power-up to call clearBonds() and erase the stored name. That gives users a way out of the stale-bond trap without a serial cable. Remember the phone side still holds its copy of the bond, so the user also has to “forget” the device in the phone’s Bluetooth settings.
Rename outside the BLE callback
Step 6 calls BLEDevice::deinit() from inside onWrite. That callback runs on the Bluetooth stack’s own task, so the code tears down the stack from within the stack. It often works, and occasionally it hangs or crashes depending on timing. A safer pattern is to record the request and do the work from loop():
volatile bool renameRequested = false;String pendingName;
class DeviceNameCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *c) override { if (!authenticated) return; pendingName = c->getValue().c_str(); renameRequested = pendingName.length() > 0; }};
void loop() { if (renameRequested) { renameRequested = false; preferences.putString("name", pendingName); ESP.restart(); // setup() reads the stored name and rebuilds everything }}Restarting is slower than deinit/init, but it rebuilds the server, services and security configuration from one code path in setup(), so nothing can be left half-configured. Put the security setup from steps 1 to 3 in a single function and call it from setup() only.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Connects without a PIN prompt | MITM requested with ESP_IO_CAP_NONE, or an old bond | Match IO capability to auth mode, clear bonds on both sides |
Auth FAILED right after connect | Phone holds a bond the ESP32 no longer has | Forget the device on the phone and pair again |
| Device disappears after a failed pairing | Failed peer still connected, advertising stopped | Disconnect on failed auth, restart advertising on disconnect |
| Writes succeed on an unpaired link | Gate relies only on an app-level flag | Add ESP_GATT_PERM_*_ENC_MITM permissions |
| Notifications never arrive | Missing or unwritable CCCD | Add BLE2902 with matching permissions |
| Random reboot after rename | Stack torn down from its own callback | Defer the rename to loop() |
Wrapping Up
The security configuration requires consistent flags across setEncryptionLevel, setAuthenticationMode, setCapability, and setStaticPIN. Any mismatch degrades silently to a weaker mode: the connection succeeds but without MITM protection. Verify in nRF Connect that the pairing type shown is “Passkey Entry”, not “Just Works”, before shipping anything.
The next step is per-characteristic access control with setAccessPermissions, which enforces encryption requirements at the GATT layer rather than relying on the application-level authenticated flag.