# # Practical 08 – Network Security

# ## 1. Demonstrate Two Different Certificates Producing the Same MD5 Hash (`toy_collision_demo.py`)
# Demonstrate Hash Collision Using Two Different Certificates

def toy_hash(b):
    return sum(b) % 256

def make_base_certs():
    cert1 = b"Certificate Alice"
    cert2 = b"Certificate Bob"
    return cert1, cert2

def main():
    cert1, cert2 = make_base_certs()

    h1 = toy_hash(cert1)
    h2 = toy_hash(cert2)

    print("Initial Hashes:")
    print("Cert1:", h1)
    print("Cert2:", h2)

    padding = (h1 - sum(cert2)) % 256
    cert2_padded = cert2 + bytes([padding])

    print("\nAfter Padding:")
    print("Cert1 Hash:", toy_hash(cert1))
    print("Cert2 Hash:", toy_hash(cert2_padded))

    print("Certificates Identical:", cert1 == cert2_padded)
    print("Collision:", toy_hash(cert1) == toy_hash(cert2_padded))

    with open("cert1.pem", "wb") as f:
        f.write(cert1)

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

if __name__ == "__main__":
    main()


# Note: This is a toy hash collision demonstration, not an actual MD5 collision. The supplied original code also uses a toy hash.

# ## 2. Computing Hash (SHA-256)
# Calculate SHA-256 Hash of a Message

import hashlib

message = "Hello Security Students".encode()

hash_digest = hashlib.sha256(message).hexdigest()

print("SHA256 Hash:", hash_digest)


# ## 3. Computing MAC
# Generate Message Authentication Code

import hmac
import hashlib

secret_key = b'shared_secret'
message = b'Important Transaction: $500'

mac = hmac.new(secret_key, message, hashlib.sha256).hexdigest()

print("Message:", message.decode())
print("MAC:", mac)


# ## 4. Computing HMAC
# Generate HMAC-SHA256

import hmac
import hashlib

key = b'super_secret_key'
msg = b'Authenticate this message'

hmac_digest = hmac.new(key, msg, hashlib.sha256).hexdigest()

print("HMAC:", hmac_digest)


# Install: No additional libraries required. All programs use Python's built-in libraries.