# Practical 7 – IoT Security
# Install: pip install pycryptodome paho-mqtt scapy

# if Crypto not found --
# python -m pip uninstall Crypto -y
# python -m pip uninstall pycryptodome -y
# python -m pip install pycryptodome

import base64
import hashlib
import hmac
from Crypto.Cipher import AES
from scapy.all import IP, TCP, Raw

# 1. Encrypt and authenticate IoT sensor data with AES-EAX
key = b"ThisIsA16ByteKey"
cipher = AES.new(key, AES.MODE_EAX)
data = b"Temperature: 28C"
encrypted, tag = cipher.encrypt_and_digest(data)
print("Encrypted:", base64.b64encode(encrypted).decode())
receiver = AES.new(key, AES.MODE_EAX, nonce=cipher.nonce)
print("Decrypted:", receiver.decrypt_and_verify(encrypted, tag).decode())

# 2. Verify message integrity and authenticity with HMAC
secret = b"iot_secret_key"
message = b"Humidity: 70%"
digest = hmac.new(secret, message, hashlib.sha256).hexdigest()
received = hmac.new(secret, message, hashlib.sha256).hexdigest()
print("Message:", message.decode())
print("HMAC:", digest)
print("Authentic?", hmac.compare_digest(digest, received))


# 3. MQTT Communication

import paho.mqtt.client as mqtt

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect("broker.hivemq.com", 1883, 60)

client.publish("iot/device1", "Temperature: 25C")
print("Message Published Successfully")

client.disconnect()

# 4. Parse a sample IoT packet locally; this does not capture network traffic
packet = (IP(src="192.0.2.10", dst="192.0.2.20")
          / TCP(sport=12345, dport=1883)
          / Raw(load=b"temperature=25C"))
print("IP:", packet[IP].src, "->", packet[IP].dst)
print("Payload:", packet[Raw].load)

# What this code does: demonstrates encrypted IoT messages, HMAC verification,
# MQTT publishing, and parsing a locally constructed sample packet.
