# Instructor-only source comparison. Unverified supplied code, not a runnable consolidated file. Personal identifiers and fixed demo key redacted. Do not run unbounded searches or direct giant exponentiation.

# %% [original cell 3]
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes

data = 'secret data to transmit'.encode()
aes_key = get_random_bytes(16)

cipher = AES.new(aes_key, AES.MODE_CTR)
ciphertext = cipher.encrypt(data)

with open("encrypted.bin", "wb") as f:
    f.write(cipher.nonce)
    f.write(ciphertext)

print("Ciphertext:", ciphertext)
print("AES key (hex):", aes_key.hex())  

# %% [original cell 5]
from Crypto.Cipher import AES
from binascii import unhexlify

# Paste the AES key printed above
aes_key = unhexlify("REPLACE_WITH_DEMO_KEY")

# Read nonce and ciphertext
with open("encrypted.bin", "rb") as f:
    nonce = f.read(8)
    ciphertext = f.read()

cipher = AES.new(aes_key, AES.MODE_CTR, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)

print("Decrypted message:", plaintext.decode('utf-8'))

# %% [original cell 8]
from Crypto.Hash import SHA256, SHA512

# Message to hash
message = "I like cats".encode()

# Compute SHA-256 hash
hash256 = SHA256.new(message).hexdigest()

# Compute SHA-512 hash
hash512 = SHA512.new(message).hexdigest()

# Print results
print("SHA256:", hash256)
print("SHA512:", hash512)

# %% [original cell 10]
from Crypto.Hash import SHA256, SHA512

# Messages to hash
msg1 = "I like cats".encode()
msg2 = "I like cars".encode()

# Compute hashes
hash256_cats = SHA256.new(msg1).hexdigest()
hash512_cats = SHA512.new(msg1).hexdigest()

hash256_cars = SHA256.new(msg2).hexdigest()
hash512_cars = SHA512.new(msg2).hexdigest()

# Print hashes
print("SHA256 (I like cats):", hash256_cats)
print("SHA512 (I like cats):", hash512_cats)
print("\nSHA256 (I like cars):", hash256_cars)
print("SHA512 (I like cars):", hash512_cars)

# Verify lengths
print("\nLength of SHA256 hash:", len(hash256_cats))  # should be 64 hex characters (256 bits)
print("Length of SHA512 hash:", len(hash512_cats))    # should be 128 hex characters (512 bits)

# %% [original cell 13]
from Crypto.Hash import SHA256

def prng_from_hash(seed, n_digits):
    """
    Generate n_digits pseudorandom hexadecimal digits from a seed using SHA-256.
    
    Args:
        seed (int or str): Initial seed value.
        n_digits (int): Number of random hex digits to generate.
    
    Returns:
        list of str: Random hexadecimal digits as strings.
    """
    # Convert seed to bytes
    state = str(seed).encode()
    digits = []

    for _ in range(n_digits):
        # Hash the current state
        h = SHA256.new(state).hexdigest()
        
        # Take the last hexadecimal digit
        digits.append(h[-1])
        
        # Update state: convert entire hash to bytes for next iteration
        state = bytes.fromhex(h) 
    
    return digits

# Example usage
seed = 20241127
random_digits = prng_from_hash(seed, 10)
print("First 10 random hex digits:", random_digits)

# %% [original cell 15]
from Crypto.Hash import SHA256
from collections import Counter

def prng_from_hash(seed, n_digits):
    """
    Generate n_digits pseudorandom hexadecimal digits from a seed using SHA-256.
    """
    state = str(seed).encode()
    digits = []

    for _ in range(n_digits):
        h = SHA256.new(state).hexdigest()
        digits.append(h[-1])          # last hex digit
        state = bytes.fromhex(h)      # update state using raw hash bytes
    
    return digits

# Replace this with your student ID
student_id = 12345678

# Generate 1,000,000 hex digits
num_digits = 1_000_000
random_digits = prng_from_hash(student_id, num_digits)

# Count occurrences of each hex digit
counter = Counter(random_digits)

# Calculate relative frequencies (%) 
relative_freq = {digit: count / 10000 for digit, count in counter.items()}

# Print results
print("Hex digit counts:")
for digit in sorted(counter.keys()):
    print(f"{digit}: {counter[digit]} times, {relative_freq[digit]:.2f}%")

# %% [original cell 17]
from Crypto.Hash import SHA256
from collections import Counter

def prng_from_hash_full(seed, n_digits):
    """
    Generate n_digits pseudorandom hexadecimal digits using SHA-256,
    using all 64 hex digits from each hash output.
    """
    state = str(seed).encode()
    digits = []

    while len(digits) < n_digits:
        h = SHA256.new(state).hexdigest()  # 64 hex digits per hash
        digits.extend(list(h))             # add all 64 digits
        state = bytes.fromhex(h)           # update state for next iteration

    return digits[:n_digits]               # trim to desired number of digits

# Example: use your student ID as seed
student_id = 12345678
num_digits = 1_000_000

random_digits = prng_from_hash_full(student_id, num_digits)

# Count occurrences and calculate relative frequencies (%)
counter = Counter(random_digits)
relative_freq = {digit: count / 10000 for digit, count in counter.items()}

# Print results
print("Hex digit counts and percentages:")
for digit in sorted(counter.keys()):
    print(f"{digit}: {counter[digit]} times, {relative_freq[digit]:.2f}%")

# %% [original cell 19]
from Crypto.Hash import SHA512
from collections import Counter

def prng_from_sha512(seed, n_digits):
    """
    Generate n_digits pseudorandom hexadecimal digits using SHA-512,
    using all 128 hex digits from each hash output.
    """
    state = str(seed).encode()
    digits = []

    while len(digits) < n_digits:
        h = SHA512.new(state).hexdigest()  # 128 hex digits per hash
        digits.extend(list(h))             # add all 128 digits
        state = bytes.fromhex(h)           # update state for next iteration

    return digits[:n_digits]               # trim to desired number of digits

# Example: use your student ID as seed
student_id = 12345678
num_digits = 1_000_000

random_digits = prng_from_sha512(student_id, num_digits)

# Count occurrences and calculate relative frequencies (%)
counter = Counter(random_digits)
relative_freq = {digit: count / 10000 for digit, count in counter.items()}

# Print results
print("Hex digit counts and percentages (SHA-512):")
for digit in sorted(counter.keys()):
    print(f"{digit}: {counter[digit]} times, {relative_freq[digit]:.2f}%")

# %% [original cell 21]
import time
from Crypto.Hash import SHA256, SHA512

def prng_sha256(seed, n_digits):
    state = str(seed).encode()
    digits = []
    while len(digits) < n_digits:
        h = SHA256.new(state).hexdigest()  # 64 hex digits per hash
        digits.extend(list(h))
        state = bytes.fromhex(h)
    return digits[:n_digits]

def prng_sha512(seed, n_digits):
    state = str(seed).encode()
    digits = []
    while len(digits) < n_digits:
        h = SHA512.new(state).hexdigest()  # 128 hex digits per hash
        digits.extend(list(h))
        state = bytes.fromhex(h)
    return digits[:n_digits]

# Parameters
student_id = 12345678
num_digits = 1_000_000

# Measure SHA-256 time
start_time = time.time()
digits_sha256 = prng_sha256(student_id, num_digits)
time_sha256 = time.time() - start_time
print(f"SHA-256: Generated {num_digits} digits in {time_sha256:.2f} seconds")

# Measure SHA-512 time
start_time = time.time()
digits_sha512 = prng_sha512(student_id, num_digits)
time_sha512 = time.time() - start_time
print(f"SHA-512: Generated {num_digits} digits in {time_sha512:.2f} seconds")

# %% [original cell 22]
# The hash-based PRNGs we implemented are **deterministic** and predictable if the seed is known, and they may leak future or past outputs. 
# They are fine for simulations or testing randomness, but **not safe for cryptographic use**. For cryptography, always use a **CSPRNG** like `Crypto.Random.get_random_bytes()`, which provides unpredictable, secure random numbers.
