# 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 2]
import hashlib, secrets

def sha256_hex(x: bytes) -> str:
    return hashlib.sha256(x).hexdigest()

attempts_for_last_hex = {}

for target in "0123456789abcdef":
    attempts = 0
    while True:
        attempts += 1
        data = secrets.token_bytes(32)
        digest = sha256_hex(data)
        if digest.endswith(target):
            attempts_for_last_hex[target] = attempts
            break

print("\nAttempts for digest ending in one hex digit:")
for k, v in attempts_for_last_hex.items():
    print(f"Ends with {k}: {v} attempts")




# %% [original cell 3]
import hashlib, secrets

def sha256_hex(x: bytes) -> str:
    return hashlib.sha256(x).hexdigest()

attempts_for_last_two = {}

hex_pairs = [a+b for a in "0123456789abcdef" for b in "0123456789abcdef"]

for pair in hex_pairs:
    print("Searching for", pair)
    attempts = 0
    while True:
        attempts += 1
        data = secrets.token_bytes(32)
        digest = sha256_hex(data)
        if digest.endswith(pair):
            attempts_for_last_two[pair] = attempts
            break

print("\nAttempts for two-hex endings:")
for k, v in attempts_for_last_two.items():
    print(f"Ends with {k}: {v}")



# %% [original cell 4]
import hashlib, secrets

def sha256_hex(x: bytes) -> str:
    return hashlib.sha256(x).hexdigest()

seen = {}   # maps last-two-hex → (input, digest)
attempts = 0

while True:
    attempts += 1
    data = secrets.token_bytes(32)
    digest = sha256_hex(data)
    tail = digest[-2:]  # last two hex digits

    if tail in seen:           # Collision found
        print("Collision found!")
        print(f"Attempts: {attempts}")
        print(f"Tail: {tail}")
        print("\nFirst digest:", seen[tail][1])
        print("Second digest:", digest)
        break
    else:
        seen[tail] = (data, digest)

# %% [original cell 6]
import os
import hashlib

# XOR helper
def xor_bytes(a, b):
    return bytes(x ^ y for x, y in zip(a, b))

# -----------------------------
# Step 1: Generate 128-bit key
# -----------------------------
key = os.urandom(16)  # 16 bytes = 128 bits

# -----------------------------
# Step 2: Pad to 1024 bits (128 bytes)
# -----------------------------
block_size = 128
key_padded = key + b"\x00" * (block_size - len(key))

# -----------------------------
# Step 3: ipad and opad
# -----------------------------
ipad = bytes([0x36] * block_size)
opad = bytes([0x5C] * block_size)

# -----------------------------
# Step 4: Manual HMAC
# -----------------------------
def hmac_sha256(key_pad, message):
    # inner = SHA256( (K xor ipad) || message )
    inner = hashlib.sha256()
    inner.update(xor_bytes(key_pad, ipad))
    inner.update(message)
    inner_hash = inner.digest()

    # outer = SHA256( (K xor opad) || inner_hash )
    outer = hashlib.sha256()
    outer.update(xor_bytes(key_pad, opad))
    outer.update(inner_hash)
    return outer.digest()

# Example message
message = b"example message"
tag = hmac_sha256(key_padded, message)

print("128-bit key:", key.hex())
print("1024-bit padded key:", key_padded.hex())
print("HMAC:", tag.hex())



# %% [original cell 9]
import os, hashlib
from collections import Counter

# -----------------------------------------------------------
# 1. MANUAL HMAC IMPLEMENTATION (required by the assignment)
# -----------------------------------------------------------
def hmac_sha256(key, message):
    block_size = 64  # 512-bit block for SHA-256

    # Pad or hash key
    if len(key) > block_size:
        key = hashlib.sha256(key).digest()
    if len(key) < block_size:
        key = key + b"\x00" * (block_size - len(key))

    ipad = bytes([0x36] * block_size)
    opad = bytes([0x5C] * block_size)

    # inner = SHA256( (key XOR ipad) || message )
    inner = hashlib.sha256()
    inner.update(bytes([a ^ b for a, b in zip(key, ipad)]))
    inner.update(message)
    inner_hash = inner.digest()

    # outer = SHA256( (key XOR opad) || inner_hash )
    outer = hashlib.sha256()
    outer.update(bytes([a ^ b for a, b in zip(key, opad)]))
    outer.update(inner_hash)

    return outer.digest()

# -----------------------------------------------------------
# 2. CSPRNG: GENERATE RANDOM HEX DIGITS USING HMAC
# -----------------------------------------------------------
def csprng_hex(length):
    key = os.urandom(32)   # 256-bit secret key
    counter = 0
    output = ""

    while len(output) < length:
        msg = counter.to_bytes(8, "big")
        block = hmac_sha256(key, msg).hex()
        output += block
        counter += 1

    return output[:length]

# -----------------------------------------------------------
# 3. CSPRNG: GENERATE RANDOM DECIMAL DIGITS USING HMAC (0–9)
# -----------------------------------------------------------
def csprng_decimal(length):
    key = os.urandom(32)
    counter = 0
    digits = ""

    while len(digits) < length:
        msg = counter.to_bytes(8, "big")
        block = hmac_sha256(key, msg)

        for b in block:
            digits += str(b % 10)
            if len(digits) == length:
                break

        counter += 1

    return digits

# -----------------------------------------------------------
# 4. UNIFORMITY TESTS
# -----------------------------------------------------------
def test_uniform_hex():
    N = 100000
    data = csprng_hex(N)
    counts = Counter(data)
    print("Hex digit frequencies:")
    for d in "0123456789abcdef":
        print(d, counts[d] / N)

def test_uniform_decimal():
    N = 100000
    data = csprng_decimal(N)
    counts = Counter(data)
    print("Decimal digit frequencies:")
    for d in "0123456789":
        print(d, counts[d] / N)

# -----------------------------------------------------------
# 5. RUN EVERYTHING
# -----------------------------------------------------------
print("Random Hex:", csprng_hex(32))
print("Random Decimal:", csprng_decimal(32))

print("\nTesting uniformity...\n")
test_uniform_hex()
print()
test_uniform_decimal()


