# Practical 8 – Network Security Practices
import hashlib
import hmac

# 1. Demonstrate a collision with a toy hash (not MD5)
def toy_hash(data):
    return sum(data) % 256

cert1 = b"Certificate Alice"
cert2 = b"Certificate Bob"
padding = (toy_hash(cert1) - sum(cert2)) % 256
cert2_padded = cert2 + bytes([padding])
print("Cert 1 hash:", toy_hash(cert1))
print("Cert 2 hash:", toy_hash(cert2_padded))
print("Certificates identical?", cert1 == cert2_padded)
print("Toy-hash collision?", toy_hash(cert1) == toy_hash(cert2_padded))

with open("cert1.pem", "wb") as file:
    file.write(cert1)
with open("cert2.pem", "wb") as file:
    file.write(cert2_padded)

# 2. Calculate a SHA-256 digest
message = b"Hello Security Students"
print("SHA-256:", hashlib.sha256(message).hexdigest())

# 3. Create a message authentication code
secret = b"shared_secret"
message = b"Important Transaction: $500"
mac = hmac.new(secret, message, hashlib.sha256).hexdigest()
print("Message:", message.decode())
print("MAC:", mac)

# 4. Calculate HMAC-SHA256
key = b"super_secret_key"
message = b"Authenticate this message"
print("HMAC:", hmac.new(key, message, hashlib.sha256).hexdigest())

# What this code does: demonstrates a toy hash collision, SHA-256 digests,
# and HMAC-based message authentication.
