The threats
A device on a network can be attacked three ways. Someone reads or fakes its traffic. Someone holding the board copies its memory, passwords and all. Someone loads their own program onto it. Each needs its own defence.
Plain MQTT on port 1883 sends bytes exactly as written. Anyone on the path can read the reading, 21.5, and the password inside the CONNECT packet. They can also pretend to be the broker. MQTT leaves security to you.
TLS on the wire
TLS fixes both problems. First the device needs something to trust. setCACert gives it a root certificate: the public key of the authority, or CA, that signed the broker's certificate. It ships inside the firmware.
connect opens a connection to port 8883 and starts the TLS handshake. The device says hello, and the broker answers with its certificate: its name, its public key and a CA's signature.
The device checks the CA's signature with the root certificate it carries, and that the name matches the host it asked for. The broker also signs the handshake with its private key. An impostor fails here and the connection stops.
Now both sides make a shared secret key. Each keeps a secret number and sends a public one: 4 one way, 10 the other. Each mixes its secret with what it got, and both arrive at 18. The key itself never crossed.
Everything after the handshake, the password and the 21.5 included, is encrypted with that key and carries a check value. The listener copies only scrambled bytes, and any change they make is detected.
Protecting the chip
The network is safe, but the board is not. The Wi-Fi password, "kite42", is compiled into the app in flash. Anyone with the board and a USB cable can copy the whole flash with esptool and read it.
Flash encryption scrambles the app with AES-256, using a 256-bit key in an eFuse: a one-time bit inside the chip. Software cannot read that key back. The chip decrypts as it runs, but a copied dump is noise.
Secure boot stops new code. You sign each image with your private key. The chip keeps only a SHA-256 digest of your public key in eFuse. At power-on it checks the signatures and refuses to run an attacker's unsigned app.
Together: TLS guards the traffic, flash encryption the secrets, secure boot the code. Over-the-air updates are checked against the same signature. In release mode JTAG and UART download are off, and eFuses can never be unburned.
What happens
;; step 1/11 · threats threat defence read or fake the traffic -> TLS copy the flash memory -> flash encryption run their own firmware -> secure boot
The card shows the six lines that open the connection. The whole sketch also joins Wi-Fi and defines HOST, ID, USER, PASS, TOPIC and ROOT_CA (paste your CA's PEM text there). In the current arduino-esp32 core WiFiClientSecure is another name for NetworkClientSecure. The key exchange uses textbook Diffie-Hellman with tiny numbers (p = 23, g = 5) so you can check it by hand. Real TLS uses an elliptic-curve version with numbers far too large to guess.