Encrypting the MQTT payload rather than the link has the advantage that the data is encrypted end to end and not just between the broker and the client.
It also means that the intermediate brokers don’t need to support SSL and that you don’t need to obtain and install certificates.
It is therefore much easier to set up and use.
As a demonstration I’ve modified the simple pub-sub script to use payload encryption.
Here is a screen shot of the script with annotations:
Note 2– First we create an encryption key – cipher_key = Fernet.generate_key(). This key is used to encrypt and decrypt and we would need to use this same key on the receiving client. In our example the sender and receiver are the same client.
Note 3-The message to be encrypted must be in bytes.
Note 4: We need to create a UTF-8 encoded string to pass as the message payload to the MQTT publish method.
Note 5– The received message is already in bytes and so we pass it straight to the decrypt function.
Note 6: We then convert the decrypted byte message to a UTF-8 string as normal.
Running the Script
When we run the script this is what we see.
By enabling client logging as follows:
def on_log(client, userdata, level, buf): print("log: ",buf) client.on_log=on_log
You can look at the message size.
You will notice that the outgoing message size is much larger when it has been encrypted.
In the example the 2 byte “on” message becomes 100 bytes when encrypted.
Using Separate Clients
If you have two separate clients a publisher and subscriber then you will need to generate the key manually, and paste it into the code on both the subscribing client and publishing client.
Open a python command prompt which you can do from the IDE.
Enter the following commands shown n the screen shot to generate a key.
Now in both the subscribe and publish scripts replace the:
cipher_key = Fernet.generate_key()
with the key you created as shown below.
You can download the actual script here.
- Python 3: An introduction to encryption
- Encryption Basic principles
- Learning about cryptography
- Introduction to MQTT Security Mechanisms
Useful Tutorials and Resources:
- The Paho MQTT Python Client-Beginners Guide
- Logging Sensor Data to a SQL Database Using Python
- Logging sensor Data to a file Using Python
- Sending JSON Data over MQTT with Python
- Checking Active MQTT Client Connections
- Simple Controllable MQTT Sensor Simulator in Python
- Sending a File Over MQTT Using Python