# Reproduces the measurements in the study. Needs: python3, pip install argon2-cffi bcrypt
# Run: python3 lab.py   (writes results.json). The GPU rates are NOT measured here: they are the published hashcat 6.2.6 / RTX 4090 figures.
import hashlib, hmac, time, os, json, struct, platform, statistics

out = {"env": {"python": platform.python_version(), "cpu": "Intel Xeon @2.30GHz (2 vCPU, cloud VM)"}}

# 1) Throughput: hashlib (OpenSSL) single thread, buffer sizes
def tput(name, size, secs=1.5):
    buf = os.urandom(size)
    h = getattr(hashlib, name)
    n = 0
    t0 = time.perf_counter()
    while time.perf_counter() - t0 < secs:
        for _ in range(200):
            h(buf).digest()
        n += 200
    dt = time.perf_counter() - t0
    return n * size / dt / 1e6, n / dt  # MB/s, hashes/s

res = {}
for size in (64, 1024, 1048576):
    for name in ("md5", "sha1", "sha256", "sha512", "sha3_256", "blake2b"):
        runs = [tput(name, size, 1.0) for _ in range(3)]
        res[f"{name}@{size}"] = {"MBps": round(statistics.median(r[0] for r in runs), 1),
                                 "hps": round(statistics.median(r[1] for r in runs))}
out["throughput"] = res

# 2) Avalanche: flip one input bit, count differing output bits
def avalanche(name, trials=20000):
    h = getattr(hashlib, name)
    tot = 0; bits = h(b"").digest_size * 8
    mn, mx = bits, 0
    for _ in range(trials):
        m = bytearray(os.urandom(64))
        a = h(bytes(m)).digest()
        i = int.from_bytes(os.urandom(2), "big") % 512
        m[i // 8] ^= 1 << (i % 8)
        b = h(bytes(m)).digest()
        d = bin(int.from_bytes(a, "big") ^ int.from_bytes(b, "big")).count("1")
        tot += d; mn = min(mn, d); mx = max(mx, d)
    return {"bits": bits, "mean_flipped": round(tot / trials, 2), "pct": round(100 * tot / trials / bits, 2), "min": mn, "max": mx}
out["avalanche"] = {n: avalanche(n) for n in ("md5", "sha1", "sha256")}

# 3) Password KDF cost on this machine
import bcrypt, argon2
from argon2 import PasswordHasher
def timeit(f, n=5):
    ts = []
    for _ in range(n):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return round(statistics.median(ts) * 1000, 2)
pw = b"correct horse battery staple"; salt = os.urandom(16)
kdf = {}
kdf["pbkdf2_sha256_600k_ms"] = timeit(lambda: hashlib.pbkdf2_hmac("sha256", pw, salt, 600000))
kdf["pbkdf2_sha512_220k_ms"] = timeit(lambda: hashlib.pbkdf2_hmac("sha512", pw, salt, 220000))
kdf["pbkdf2_sha1_1400k_ms"] = timeit(lambda: hashlib.pbkdf2_hmac("sha1", pw, salt, 1400000))
for c in (10, 12):
    kdf[f"bcrypt_cost{c}_ms"] = timeit(lambda: bcrypt.hashpw(pw, bcrypt.gensalt(c)))
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
kdf["argon2id_19MiB_t2_p1_ms"] = timeit(lambda: ph.hash("correct horse battery staple"))
for m, tc in ((47104, 1), (12288, 3)):
    p2 = PasswordHasher(time_cost=tc, memory_cost=m, parallelism=1)
    kdf[f"argon2id_{m//1024}MiB_t{tc}_p1_ms"] = timeit(lambda: p2.hash("correct horse battery staple"))
out["kdf"] = kdf

# 4) Length extension on H(secret||msg) - pure python SHA-256 w/ settable state
K = [int(x,16) for x in """428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5 d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174 e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da 983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967 27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85 a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070 19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3 748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2""".split()]
M = 0xffffffff
def rotr(x,n): return ((x>>n)|(x<<(32-n))) & M
def compress(state, block):
    w = list(struct.unpack(">16I", block))
    for i in range(16,64):
        s0 = rotr(w[i-15],7)^rotr(w[i-15],18)^(w[i-15]>>3)
        s1 = rotr(w[i-2],17)^rotr(w[i-2],19)^(w[i-2]>>10)
        w.append((w[i-16]+s0+w[i-7]+s1) & M)
    a,b,c,d,e,f,g,h = state
    for i in range(64):
        S1 = rotr(e,6)^rotr(e,11)^rotr(e,25); ch=(e&f)^((~e)&g)
        t1=(h+S1+ch+K[i]+w[i])&M
        S0 = rotr(a,2)^rotr(a,13)^rotr(a,22); mj=(a&b)^(a&c)^(b&c)
        t2=(S0+mj)&M
        h,g,f,e,d,c,b,a = g,f,e,(d+t1)&M,c,b,a,(t1+t2)&M
    return [(x+y)&M for x,y in zip(state,[a,b,c,d,e,f,g,h])]
def pad(n): 
    p = b"\x80" + b"\x00" * ((55 - n) % 64) + struct.pack(">Q", n*8)
    return p
def sha_from_state(state, data, prior_len):
    msg = data + pad(prior_len + len(data))
    for i in range(0, len(msg), 64): state = compress(state, msg[i:i+64])
    return struct.pack(">8I", *state)

secret = os.urandom(16)
msg = b"user=guest&amount=10"
tag = hashlib.sha256(secret + msg).digest()          # vulnerable MAC
ext = b"&amount=1000000&admin=true"
# attacker knows: msg, tag, len(secret)=16, not the secret
glue = pad(16 + len(msg))
forged_msg = msg + glue + ext
state = list(struct.unpack(">8I", tag))
forged_tag = sha_from_state(state, ext, 16 + len(msg) + len(glue))
valid = hashlib.sha256(secret + forged_msg).digest() == forged_tag
hm_ok = hmac.compare_digest(hmac.new(secret, forged_msg, hashlib.sha256).digest(), forged_tag)
out["length_extension"] = {"forged_valid_against_sha256(secret||m)": valid, "forged_valid_against_hmac": hm_ok,
                           "forged_message_hex": forged_msg.hex()}
# sanity: own compress equals hashlib
assert sha_from_state([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19], b"abc", 0) == hashlib.sha256(b"abc").digest()

# 5) Brute-force model: time to exhaust keyspaces at measured + published rates
out["rates_published_rtx4090_hashcat_6_2_6"] = {"md5": 164.1e9, "sha1": 50.6387e9, "sha256": 21.9755e9, "sha512": 7.4834e9, "bcrypt_cost5": 184.0e3}
def years(space, rate): return space / rate
space8 = 95**8
out["exhaust_8char_95_alphabet_seconds_single_4090"] = {k: round(space8 / v, 1) for k, v in out["rates_published_rtx4090_hashcat_6_2_6"].items()}
space10 = 95**10
out["exhaust_10char_95_alphabet_hours_single_4090"] = {k: round(space10 / v / 3600, 1) for k, v in out["rates_published_rtx4090_hashcat_6_2_6"].items()}
json.dump(out, open("results.json", "w"), indent=1)
print(json.dumps(out, indent=1)[:6000])
