Lecture 3.2: Implementing Secure Communication

Introduction

Good morning, everyone! It’s a pleasure to see you all again as we continue our deep dive into the world of LoRa technology and LilyGO devices. Over the past few lectures, we’ve built a solid foundation by understanding the basics of LoRa communication, configuring our devices, and exploring advanced features like spread factor, coding rate, and transmission power. Today, we’re going to venture into a critical aspect of any communication system—security.

Imagine deploying a network of sensors across a city to monitor air quality. The data collected is invaluable, not just for environmental agencies but potentially for businesses and policymakers. Now, consider what could happen if that data were intercepted, altered, or misused by unauthorized parties. The consequences could range from misinformation to severe breaches of privacy and trust.

In our interconnected world, securing data transmission isn’t just an optional enhancement—it’s a necessity. Whether you’re transmitting sensitive information or simply want to ensure the integrity of your data, implementing robust security measures is paramount.

Today’s lecture is all about empowering you to protect your LoRa networks. We’ll explore encryption methods, delve into the intricacies of key management, and walk through the practical steps of setting up secure data transmission using AES encryption on your LilyGO devices.

So, let’s embark on this journey to fortify our communication systems, ensuring that the data we transmit is as secure as the applications we envision.

 

Section 1: The Importance of Secure Communication in IoT Networks

Before we delve into the technical aspects, it’s essential to understand why security is so crucial in the context of IoT and LoRa networks.

Threat Landscape

Eavesdropping: Unauthorized entities intercepting your data transmissions.
Data Tampering: Malicious actors altering the data, leading to misinformation or triggering unintended actions.
Replay Attacks: Intercepted valid data is re-transmitted, potentially causing system malfunctions.
Unauthorized Access: Gaining control over devices to manipulate system behaviour or extract sensitive information.

Consequences of Insecurity

Privacy Violations: Leakage of personal or sensitive data.
Financial Loss: Costs associated with data breaches, including mitigation and legal liabilities.
Reputation Damage: Loss of trust from users or clients due to security lapses.
Operational Disruption: Interference with system functionality, leading to downtime or unsafe conditions.

Regulatory Compliance

GDPR, HIPAA, and Other Regulations: Many regions have stringent laws governing data protection, especially when personal data is involved.
Industry Standards: Compliance with standards like ISO/IEC 27001 for information security management.

Ethical Responsibility

As developers and engineers, we have a duty to protect the data and systems we build, ensuring they serve their intended purpose without causing harm.

 

Section 2: Fundamentals of Encryption and Key Management

To secure our LoRa communications, we need to employ encryption—a method of converting data into a form that can only be understood by authorized parties.

What is Encryption?

Definition: Encryption is the process of converting plaintext (readable data) into ciphertext (encoded data) using an algorithm and an encryption key.
Purpose: Ensures that even if data is intercepted, it cannot be understood without the corresponding decryption key.

Types of Encryption

1. Symmetric Encryption

– Characteristics:
– Uses the same key for both encryption and decryption.
– Faster and less computationally intensive.
– Examples:
– AES (Advanced Encryption Standard)
– DES (Data Encryption Standard)
– Considerations:
– Key distribution can be challenging since both parties need to securely share the secret key.

2. Asymmetric Encryption

– Characteristics:
– Uses a pair of keys—a public key for encryption and a private key for decryption.
– More secure for key distribution but computationally heavier.
– Examples:
– RSA (Rivest–Shamir–Adleman)
– ECC (Elliptic Curve Cryptography)
– Considerations:
– Not commonly used for encrypting large amounts of data due to computational overhead.

Why Symmetric Encryption for LoRa?

Efficiency: LoRa devices often have limited processing power and energy resources. Symmetric encryption algorithms like AES are more suitable for such environments.
– Feasibility: The overhead of asymmetric encryption may not be practical for low-power, resource-constrained devices.

Key Management

– Importance: The security of encryption relies heavily on how well the keys are managed.
– Challenges:
– Securely generating and storing keys.
– Distributing keys without exposing them to unauthorized parties.
– Periodically updating keys to mitigate the risk of compromise.

Key Management Strategies

1. Pre-Shared Keys (PSK)

Approach: Keys are generated and shared between parties before communication begins.
Advantages: Simple to implement.
Disadvantages: Not scalable for large networks; risk if keys are exposed.

2. Key Derivation Functions

– Approach: Generate session keys from a master key using cryptographic functions.
Advantages: Enhances security by limiting the exposure of the master key.
– Disadvantages: Adds computational complexity.

3. Over-The-Air (OTA) Key Distribution

Approach: Keys are distributed through secure channels during operation.
Advantages: Facilitates key updates and scalability.
Disadvantages: Requires robust security mechanisms to prevent interception.

Best Practices for Key Management

Use Strong Keys: Generate keys using secure random number generators.
Secure Storage: Store keys in secure memory or hardware security modules if available.
Limit Key Exposure: Minimize the number of times keys are handled or transmitted.
Regular Rotation: Change keys periodically to reduce the window of vulnerability.
Access Control: Restrict who or what can access the keys within your system.

 

Section 3: Introduction to AES Encryption

Now that we’ve established the importance of encryption and key management, let’s focus on AES (Advanced Encryption Standard), which we’ll use to secure our LoRa communications.

What is AES?

Background: AES is a symmetric block cipher established by the U.S. National Institute of Standards and Technology (NIST) in 2001.
Block Size: Operates on fixed block sizes of 128 bits (16 bytes).
Key Sizes: Supports key lengths of 128, 192, or 256 bits.
Security: Considered secure and is widely adopted in various security protocols.

Modes of Operation

Since AES operates on fixed-size blocks, modes of operation define how to encrypt data longer or shorter than the block size.

– ECB (Electronic Codebook)

Characteristics: Simplest mode; each block is encrypted independently.
Disadvantages: Patterns in data can be discernible; not recommended for secure communication.

– CBC (Cipher Block Chaining)

Characteristics: Each block is XORed with the previous ciphertext block before encryption.
Advantages: Provides better security than ECB.
Requires: An initialization vector (IV) for the first block.

CFB (Cipher Feedback) and OFB (Output Feedback)

Characteristics: Turn block ciphers into stream ciphers.
Advantages: Suitable for encrypting data of arbitrary length.

– CTR (Counter)

Characteristics: Uses a counter value that changes with each block.
Advantages: Allows for parallel encryption and decryption; good performance.

Choosing the Right Mode

For our applications:

CTR Mode: Often preferred for its efficiency and simplicity.
CBC Mode: Provides good security but may introduce latency due to its sequential nature.

Initialization Vector (IV)

Purpose: Ensures that the same plaintext block encrypts to different ciphertext when encrypted multiple times.
– Requirements:
– Should be unique and, in some modes, unpredictable.
– In CTR mode, it often serves as the initial counter value.

 

Section 4: Setting Up AES Encryption on LilyGO Devices

Let’s move on to the practical aspect of implementing AES encryption on our LilyGO devices.

Development Environment

Hardware: Two LilyGO devices (e.g., T-Beam and T-Deck) with LoRa capabilities.
Software: Arduino IDE configured for ESP32 development.

Required Libraries

AESLib: A library that provides AES encryption functions compatible with Arduino.

Installation:
1. Open the Arduino IDE.
2. Navigate to Sketch > Include Library > Manage Libraries.
3. Search for “AESLib”.
4. Install the library by Mark Tillotson.

Understanding the AESLib Library

Functions:

– `aes128_enc_single()`: Encrypts a single 16-byte block.
– `aes128_dec_single()`: Decrypts a single 16-byte block.
– `aes128_cbc_encrypt()`: Encrypts data using CBC mode.
– `aes128_cbc_decrypt()`: Decrypts data using CBC mode.

– Data Handling: Operates on byte arrays.

Implementing AES Encryption

We’ll start by creating two sketches:

1. Sender: Encrypts data and transmits it over LoRa.
2. Receiver: Receives data and decrypts it.

Section 5: Coding the Sender

Step 1: Define the Key and IV

Key: A 16-byte array for AES-128.
IV: A 16-byte initialization vector.

“`cpp
#include <SPI.h>
#include <LoRa.h>
#include <AESLib.h>

byte aes_key[] = { 0x00, 0x01, 0x02, …, 0x0F }; // Replace with your 16-byte key
byte aes_iv[] = { 0xF0, 0xE1, 0xD2, …, 0x00 }; // Replace with your 16-byte IV
“`

Security Note: Never hardcode keys in production code. For demonstration purposes, we’re using fixed keys.

Step 2: Initialize LoRa and AES

“`cpp
void setup() {
Serial.begin(115200);
while (!Serial);

// Initialize LoRa
if (!LoRa.begin(915E6)) { // Use your regional frequency
Serial.println(“Starting LoRa failed!”);
while (1);
}

// Print confirmation
Serial.println(“LoRa Initialised with AES Encryption”);
}
“`

Step 3: Encrypt and Send Data

Let’s create a function to encrypt a message and send it.

“`cpp
void encryptAndSend(String message) {
// Convert message to byte array
byte plaintext[32];
message.getBytes(plaintext, 32);

// Prepare buffers
int messageLength = message.length();
int paddedLength = ((messageLength + 15) / 16) * 16; // Pad to multiple of 16
byte ciphertext[paddedLength];

// Encrypt data
aes128_cbc_encrypt(plaintext, ciphertext, paddedLength, aes_key, aes_iv);

// Send data over LoRa
LoRa.beginPacket();
LoRa.write(ciphertext, paddedLength);
LoRa.endPacket();

Serial.println(“Encrypted message sent.”);
}
“`

Step 4: Main Loop

Send encrypted messages periodically.

“`cpp
void loop() {
String message = “Hello Secure LoRa!”;
encryptAndSend(message);
delay(5000); // Wait for 5 seconds
}
“`

 

Section 6: Coding the Receiver

**Step 1: Define the Same Key and IV**

Ensure the receiver has the same key and IV.

“`cpp
#include <SPI.h>
#include <LoRa.h>
#include <AESLib.h>

byte aes_key[] = { 0x00, 0x01, 0x02, …, 0x0F }; // Must match sender
byte aes_iv[] = { 0xF0, 0xE1, 0xD2, …, 0x00 }; // Must match sender
“`

Step 2: Initialize LoRa and AES

“`cpp
void setup() {
Serial.begin(115200);
while (!Serial);

// Initialize LoRa
if (!LoRa.begin(915E6)) { // Use your regional frequency
Serial.println(“Starting LoRa failed!”);
while (1);
}

// Print confirmation
Serial.println(“LoRa Receiver with AES Decryption”);
}
“`

Step 3: Receive and Decrypt Data

Create a function to receive and decrypt messages.

“`cpp
void receiveAndDecrypt() {
int packetSize = LoRa.parsePacket();
if (packetSize) {
// Prepare buffer
byte ciphertext[256]; // Adjust size as needed
int len = 0;

// Read the incoming data
while (LoRa.available()) {
ciphertext[len++] = LoRa.read();
}

// Decrypt data
byte decryptedText[len];
aes128_cbc_decrypt(ciphertext, decryptedText, len, aes_key, aes_iv);

// Convert to String
String message = “”;
for (int i = 0; i < len; i++) {
message += (char)decryptedText[i];
}

Serial.print(“Received decrypted message: “);
Serial.println(message);
}
}
“`

Step 4: Main Loop

Call the receive function continuously.

“`cpp
void loop() {
receiveAndDecrypt();
}
“`

 

Section 7: Testing and Verification

Step 1: Upload Code to Devices

– Sender: Upload the sender sketch to one LilyGO device.
Receiver: Upload the receiver sketch to the other device.

Step 2: Monitor Serial Output

– Open the Serial Monitor for both devices.
Sender Output:
– Should display “Encrypted message sent.”
Receiver Output:
– Should display “Received decrypted message: Hello Secure LoRa!”

Step 3: Verify Encryption

Interception Test:
– Use a third device to attempt to receive the LoRa packets without the key.
– The intercepted data should be unintelligible.

Step 4: Tampering Test

Modify Ciphertext:
– If possible, alter the ciphertext before it reaches the receiver.
– The decryption should fail or produce garbled output, indicating data integrity is compromised.

 

Section 8: Enhancing Security

Message Authentication Codes (MAC)

Purpose: Ensure data integrity and authenticity.
Implementation: Use HMAC (Hash-based Message Authentication Code) with a shared secret.

Adding MAC to the Message

1. Compute HMAC on Plaintext

“`cpp
#include <sha256.h>

byte hmac_key[] = { /* Your HMAC key */ };

void computeHMAC(byte *data, int dataLen, byte *hmac) {
SHA256 sha256;
sha256.initHmac(hmac_key, sizeof(hmac_key));
sha256.write(data, dataLen);
sha256.resultHmac(hmac, sizeof(hmac_key));
}
“`

2. Append HMAC to Ciphertext

“`cpp
byte hmac[32];
computeHMAC(plaintext, messageLength, hmac);

// Combine ciphertext and HMAC
byte payload[paddedLength + 32];
memcpy(payload, ciphertext, paddedLength);
memcpy(payload + paddedLength, hmac, 32);

// Send payload
LoRa.beginPacket();
LoRa.write(payload, sizeof(payload));
LoRa.endPacket();
“`

Validating HMAC on Receiver

1. Extract Ciphertext and HMAC

“`cpp
int ciphertextLen = len – 32;
byte receivedCiphertext[ciphertextLen];
byte receivedHMAC[32];

memcpy(receivedCiphertext, ciphertext, ciphertextLen);
memcpy(receivedHMAC, ciphertext + ciphertextLen, 32);
“`

2. Decrypt and Compute HMAC

“`cpp
// Decrypt data
byte decryptedText[ciphertextLen];
aes128_cbc_decrypt(receivedCiphertext, decryptedText, ciphertextLen, aes_key, aes_iv);

// Compute HMAC
byte computedHMAC[32];
computeHMAC(decryptedText, ciphertextLen, computedHMAC);

// Compare HMACs
if (memcmp(receivedHMAC, computedHMAC, 32) == 0) {
Serial.print(“Valid message: “);
Serial.println((char*)decryptedText);
} else {
Serial.println(“HMAC validation failed. Message integrity compromised.”);
}
“`

Security Benefits

Data Integrity: Ensures that the message hasn’t been altered.
Authentication: Confirms that the message is from a trusted source.

 

Section 9: Secure Key Management Practices

Key Generation

– Use a cryptographically secure random number generator.
– Avoid predictable or simple keys.

Key Storage

– In Code: Not recommended for production.
– Secure Elements: Use hardware security modules if available.
External Storage: Store keys on an SD card with encryption.

Key Distribution

– Physical Transfer: Secure but impractical for large deployments.
Pre-Shared Keys: Suitable for small, controlled environments.
– Key Exchange Protocols: Implement Diffie-Hellman or other key exchange methods, keeping in mind resource constraints.

Key Rotation

– Regularly update keys to minimize the risk of compromise.
– Implement mechanisms to distribute new keys securely.

Access Control

– Limit who can access the keys.
– Use authentication mechanisms to prevent unauthorized device access.

Section 10: Legal and Ethical Considerations

Regulatory Compliance

Export Restrictions: Some countries have regulations on the export of encryption technologies.
Data Protection Laws: Ensure compliance with laws like GDPR, which mandate data security measures.

Ethical Responsibility

Privacy: Respect user privacy by safeguarding data.
Transparency: Inform users about the security measures in place.
Responsibility: Be proactive in addressing vulnerabilities.

 

Conclusion

In today’s interconnected world, the security of our communication systems is more critical than ever. By implementing encryption and proper key management, we not only protect the data we transmit but also uphold the trust placed in us by users, clients, and the broader community.

We’ve explored the practical steps of securing our LoRa communications using AES encryption on LilyGO devices. From understanding the fundamental principles of encryption to coding and testing our secure transmission, we’ve equipped ourselves with the tools needed to build robust and secure IoT networks.

As you continue to develop your projects, I encourage you to prioritize security from the outset. Consider the potential threats, implement best practices, and stay informed about the latest developments in cybersecurity.

Remember, security isn’t a one-time setup but an ongoing commitment. Regularly assess your systems, update your practices, and be vigilant against emerging threats.

 

Questions and Discussion

Now, let’s open the floor for any questions or insights you’d like to share.

Question: What are some alternatives to AES if we require even more lightweight encryption for resource-constrained devices?

Answer: While AES is efficient, there are lighter alternatives like ChaCha20 or Salsa20, which offer good performance on devices with limited processing power. Additionally, algorithms like Speck and Simon, developed by the NSA for constrained environments, might be considered, but their use is controversial due to potential security concerns.

Question: How can we securely update keys in devices deployed in the field without physical access?

Answer: Implementing a secure key exchange or update protocol is essential. You can use asymmetric cryptography for initial authentication to establish a secure channel, then update symmetric keys. However, this adds complexity and requires careful implementation to prevent vulnerabilities.

Question: Is it possible to use LoRaWAN for built-in security features instead of implementing our own encryption?

Answer: Yes, LoRaWAN includes security features like end-to-end encryption and key management protocols. If your application can accommodate the LoRaWAN protocol and infrastructure, leveraging its built-in security might be advantageous. However, for point-to-point or custom networks, implementing your own security measures is necessary.

 

Additional Resources

“Cryptography Engineering” by Niels Ferguson, Bruce Schneier, and Tadayoshi Kohno: A comprehensive guide on practical cryptography.
AESLib Documentation and Examples: Explore more about the library used in our examples.
LoRa Alliance Security Guidelines: Provides best practices for securing LoRa and LoRaWAN networks.

 

Closing Remarks

As we wrap up today’s lecture, I want to emphasize that security is not just about protecting data — it’s about fostering trust and enabling innovation without compromise. By integrating robust security measures into our IoT projects, we open doors to new possibilities while safeguarding the integrity and privacy of the information we handle.

I encourage you to continue exploring the realm of cybersecurity, stay curious, and never hesitate to ask questions or seek guidance.

In our next lecture, we’ll build upon what we’ve learned by exploring multi-hop routing and data aggregation in mesh networks. We’ll see how to extend our communication capabilities while maintaining the security principles we’ve discussed today.

Thank you for your engagement and dedication. I look forward to seeing the secure and innovative solutions you’ll develop.

See you all in the next lecture!

 

 

‘Fix the broken countries of the west through increased transparency, design and professional skills. Support Skills Gap Trainer.’


To see our Donate Page, click https://skillsgaptrainer.com/donate

To see our Twitter / X Channel, click https://x.com/SkillsGapTrain

To see our Instagram Channel, click https://www.instagram.com/skillsgaptrainer/

To see some of our Udemy Courses, click SGT Udemy Page

To see our YouTube Channel, click https://www.youtube.com/@skillsgaptrainer

Scroll to Top