# Program 1: AES Encryption for IoT Sensor Data
# Secure IoT communication using AES symmetric encryption. Learning outcome: How IoT sensor data can be protected in transit. 
from Crypto.Cipher import AES 
import base64 
# AES requires 16/24/32 byte key 
key = b"ThisIsA16ByteKey" 
cipher = AES.new(key, AES.MODE_EAX) 
# IoT sensor data (example: temperature) 
sensor_data = "Temperature: 28C" 
# Encrypt 
ciphertext, tag = cipher.encrypt_and_digest(sensor_data.encode()) 
nonce = cipher.nonce 
print("Encrypted Data:", base64.b64encode(ciphertext).decode()) # Decrypt 
cipher_dec = AES.new(key, AES.MODE_EAX, nonce=nonce) 
decrypted_data = cipher_dec.decrypt(ciphertext).decode() 
print("Decrypted Data:", decrypted_data)




# Program 2: HMAC for Data Integrity 
# Ensure IoT messages are not tampered with using HMAC (Hash-based Message  Authentication Code). 
# Learning outcome: How IoT devices verify integrity & authenticity of messages. 
import hmac 
import hashlib 
# Secret key shared between IoT device and server 
secret_key = b"iot_secret_key" 
# IoT message 
message = b"Humidity: 70%" 
# Generate HMAC 
hmac_digest = hmac.new(secret_key, message, hashlib.sha256).hexdigest() 
print("Message:", message.decode()) 
print("Generated HMAC:", hmac_digest) 
# Receiver verification 
received_hmac = hmac.new(secret_key, message, hashlib.sha256).hexdigest()
if hmac.compare_digest(hmac_digest, received_hmac): 
    print(" Message is authentic") 
else: 
    print(" Message tampered!") 



# Program 3: MQTT Communication with TLS Security
# Demonstrates secure IoT communication using the MQTT protocol with Python. Learning outcome: Understand secure IoT communication over TLS and MQTT. 
import paho.mqtt.client as mqtt 
# Define callbacks 
def on_connect(client, userdata, flags, rc): 
 print("Connected with result code " + str(rc)) 
 client.subscribe("iot/device1") 
def on_message(client, userdata, msg): 
 print("Received:", msg.topic, msg.payload.decode()) 
# Create client with TLS 
client = mqtt.Client() 
client.tls_set() # Enables TLS encryption
# Connect to public MQTT broker (you can set up Mosquitto locally) client.connect("test.mosquitto.org", 8883, 60) 
# Start loop 
client.loop_start() 
# Publish encrypted sensor message 
client.publish("iot/device1", "Secure Temperature Data: 25C") 



# Program 4: Packet Sniffing in IoT Traffic
# This shows how attackers can capture IoT packets if communication is not secured. from scapy.all import sniff 
# Callback function to process each captured packet 
def packet_callback(packet): 
 if packet.haslayer("IP"): 
    src = packet["IP"].src 
    dst = packet["IP"].dst 
    print(f"[IP Packet] {src} → {dst}") 
 if packet.haslayer("Raw"): # application data 
    payload = packet["Raw"].load 
    print("Payload:", payload) 
print(" Sniffing IoT traffic... Press Ctrl+C to stop") 
# Capture 10 packets (you can increase for live demo) 
sniff(prn=packet_callback, count=10)