"""
toycrypto.py -- cryptography as black boxes, built only from the standard library, for TEACHING:
message authentication codes (HMAC-SHA256), authenticated encryption (encrypt-then-MAC with an HMAC
keystream), key derivation, password-derived keys, Diffie-Hellman key agreement and Schnorr signatures
in the 2048-bit RFC 3526 group.

[Questions this module answers]
  Lecture 26 treats cryptography as a set of black boxes with precise
  promises: "nobody without the key can produce a valid tag", "nobody
  without the key learns anything about the plaintext except its length".
  What do those boxes look like as functions, and what do they NOT promise?

[The boxes]
  mac(key, data) -> 32-byte tag               integrity + authenticity (shared key)
  seal(key, value, nonce, ad) -> bytes         confidentiality + integrity (shared key);
  open_sealed(key, blob, ad) -> value | None   `ad` = associated data: authenticated, not hidden
  kdf(key, *labels) -> 32 bytes                one master key -> many independent keys
  password_key(password, salt) -> 32 bytes     a deliberately slow function of a password
  dh_keypair(rng), dh_shared(x, Y)             two strangers agree on a key over a public channel
  schnorr_keypair(rng), sign(x, msg), verify(y, msg, sig)   public-key signatures

[What they do NOT promise] (each is a lesson of the lecture)
  - No box knows about TIME: a valid message recorded yesterday is still
    valid today. Freshness (nonces, counters, timestamps) is the protocol's job.
  - No box knows WHO: Diffie-Hellman gives a key shared with "whoever is at
    the other end" -- possibly a man in the middle. Authentication is the
    protocol's job.
  - Encryption hides content, not length, timing or who talks to whom.

[WARNING] Teaching code only. The constructions are standard in shape
  (HMAC, encrypt-then-MAC, the RFC 3526 group, Schnorr), but this module is
  not constant-time, uses short exponents for speed, and takes its
  randomness from a SEEDED generator so that the demos are reproducible.
  Real systems use vetted libraries and the operating system's randomness
  (os.urandom / secrets); never this module.

[Python tip] hmac.compare_digest compares two byte strings in time that does not depend on where
  they first differ, so an attacker cannot learn a valid tag byte by byte from response times.

[DS link] Lecture 26 sections 2-3. Messages are marshalled with Lecture 3's wire.py.
"""

import hashlib
import hmac
import random

import course_path
course_path.use("lecture03")

import wire

# ----------------------------------------------------------------------------------------------
# Symmetric boxes
# ----------------------------------------------------------------------------------------------

def mac(key, data):
    """HMAC-SHA256 of `data` (bytes) under `key` (bytes). [Returns] 32 bytes."""
    return hmac.new(key, data, hashlib.sha256).digest()


def mac_ok(key, data, tag):
    """[Returns] True iff `tag` is the MAC of `data` under `key` (constant-time comparison)."""
    return hmac.compare_digest(mac(key, data), tag)


def kdf(key, *labels):
    """Derive an independent 32-byte key from `key` for a purpose named by `labels`.

    [Idea] kdf(k, "enc") and kdf(k, "mac") look unrelated to anyone without k, so
      one secret can safely serve several purposes (never use one key for two jobs).
    """
    return mac(key, "|".join(str(x) for x in labels).encode())


def password_key(password, salt, iterations=2000):
    """A key derived from a password with PBKDF2-HMAC-SHA256.

    [Idea] Deliberately SLOW (many iterations) so that someone who steals a hash or
      records a message encrypted under it must pay for every password guess; the
      SALT (here the user's name) makes each user's key different for the same
      password. Real systems use 10^5+ iterations or memory-hard functions.
    """
    return hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), iterations)


def _keystream(key, nonce, n):
    out = bytearray()
    counter = 0
    while len(out) < n:
        out += mac(key, nonce + counter.to_bytes(8, "big"))
        counter += 1
    return bytes(out[:n])


def seal(key, value, nonce, ad=b""):
    """Authenticated encryption of any wire-marshallable `value`.

    [Idea] Encrypt-then-MAC: c = marshal(value) XOR keystream(k_enc, nonce);
      tag = HMAC(k_mac, ad | nonce | c). Two derived keys, never the same key twice.
    [Parameters] nonce : bytes, unique per message under this key (a counter is fine);
      ad : associated data that is authenticated but sent in the clear (e.g. a header).
    [Returns] bytes = nonce length (1) | nonce | ciphertext | tag (32).
    [Edge cases] Reusing a nonce with the same key reveals the XOR of two plaintexts --
      the classic stream-cipher failure; callers must never do it.
    """
    k_enc, k_mac = kdf(key, "enc"), kdf(key, "mac")
    pt = wire.dumps(value)
    ct = bytes(a ^ b for a, b in zip(pt, _keystream(k_enc, nonce, len(pt))))
    tag = mac(k_mac, ad + b"|" + nonce + b"|" + ct)
    return bytes([len(nonce)]) + nonce + ct + tag


def open_sealed(key, blob, ad=b""):
    """Inverse of seal(). [Returns] the value, or None if the blob was not sealed under this key and ad.

    [Edge cases] Any modification of nonce, ciphertext, tag or ad gives None -- the
      receiver learns nothing else (no error oracle telling WHERE it failed).
    """
    if not isinstance(blob, (bytes, bytearray)) or len(blob) < 1 + 32:
        return None
    n = blob[0]
    nonce, ct, tag = blob[1:1 + n], blob[1 + n:-32], blob[-32:]
    k_enc, k_mac = kdf(key, "enc"), kdf(key, "mac")
    if not mac_ok(k_mac, ad + b"|" + bytes(nonce) + b"|" + bytes(ct), bytes(tag)):
        return None
    pt = bytes(a ^ b for a, b in zip(ct, _keystream(k_enc, bytes(nonce), len(ct))))
    try:
        return wire.loads(pt)
    except wire.MarshalError:
        return None


class Rng:
    """A seeded source of keys and nonces, so that every demo run is identical (teaching only)."""

    def __init__(self, seed):
        self.r = random.Random(seed)

    def key(self):
        return bytes(self.r.randrange(256) for _ in range(32))

    def nonce(self, n=12):
        return bytes(self.r.randrange(256) for _ in range(n))

    def bits(self, k):
        return self.r.getrandbits(k)


# ----------------------------------------------------------------------------------------------
# Public-key boxes in the RFC 3526 2048-bit group
# ----------------------------------------------------------------------------------------------

P = int("".join("""
FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1 29024E08 8A67CC74 020BBEA6 3B139B22
514A0879 8E3404DD EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245 E485B576 625E7EC6
F44C42E9 A637ED6B 0BFF5CB6 F406B7ED EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D
C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F 83655D23 DCA3AD96 1C62F356 208552BB
9ED52907 7096966D 670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B E39E772C 180E8603
9B2783A2 EC07A28F B5C55DF0 6F4C52C9 DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510
15728E5A 8AACAA68 FFFFFFFF FFFFFFFF""".split()), 16)
Q = (P - 1) // 2          # P is a "safe prime": Q is prime too
G = 2                     # generates the subgroup of order Q (2 is a square mod this P)
SECRET_BITS = 320         # short secret exponents, for speed (see the WARNING above)


def _int_bytes(x):
    return x.to_bytes((x.bit_length() + 7) // 8 or 1, "big")


def dh_keypair(rng):
    """[Returns] (secret x, public X = G^x mod P)."""
    x = rng.bits(SECRET_BITS) | 1
    return x, pow(G, x, P)


def dh_shared(x, Y):
    """Both sides compute G^(xy) mod P; a KDF turns it into a 32-byte key.

    [Edge cases] Y must be checked to lie in the subgroup (1 < Y < P - 1 and Y^Q = 1);
      a value outside it would leak bits of x. The check is cheap insurance.
    """
    if not 1 < Y < P - 1 or pow(Y, Q, P) != 1:
        raise ValueError("public value not in the group")
    return kdf(_int_bytes(pow(Y, x, P)), "dh")


def schnorr_keypair(rng):
    """[Returns] (secret x, public y = G^x mod P)."""
    x = rng.bits(SECRET_BITS) | 1
    return x, pow(G, x, P)


def _challenge(r, msg):
    return int.from_bytes(hashlib.sha256(_int_bytes(r) + b"|" + msg).digest(), "big") % Q


def sign(x, msg):
    """Schnorr signature of bytes `msg` with secret x. [Returns] (e, s).

    [Idea] Commit to r = G^k, take the challenge e = H(r, msg), answer s = k + x e mod Q.
      Only someone who knows x can answer every challenge. The nonce k is derived from
      (x, msg), so signing twice gives the same signature and k is never reused across
      different messages (reusing k for two messages reveals x).
    """
    k = int.from_bytes(mac(_int_bytes(x), b"nonce|" + msg), "big") % (1 << SECRET_BITS) | 1
    r = pow(G, k, P)
    e = _challenge(r, msg)
    return e, (k + x * e) % Q


def verify(y, msg, sig):
    """[Returns] True iff sig = (e, s) is a valid signature of msg under public key y.

    [Idea] G^s * y^(-e) = G^(k + x e - x e) = G^k = r, so the verifier can recompute r and
      check that e = H(r, msg). y^(-e) = y^(Q - e) because y has order Q.
    """
    e, s = sig
    if not (0 <= e < Q and 0 <= s < Q):
        return False
    r = pow(G, s, P) * pow(y, Q - e, P) % P
    return _challenge(r, msg) == e


def _selftest():
    checks = 0
    rng = Rng(1)
    k = rng.key()
    blob = seal(k, ("pay", 10, "carol"), rng.nonce(), ad=b"hdr")
    assert open_sealed(k, blob, ad=b"hdr") == ("pay", 10, "carol")
    checks += 1
    bad = bytearray(blob)
    bad[20] ^= 1
    assert open_sealed(k, bytes(bad), ad=b"hdr") is None and open_sealed(k, blob, ad=b"other") is None
    assert open_sealed(rng.key(), blob, ad=b"hdr") is None
    checks += 1
    xa, ya = dh_keypair(rng)
    xb, yb = dh_keypair(rng)
    assert dh_shared(xa, yb) == dh_shared(xb, ya)
    checks += 1
    x, y = schnorr_keypair(rng)
    sig = sign(x, b"hello")
    assert verify(y, b"hello", sig) and not verify(y, b"hellO", sig) and not verify(ya, b"hello", sig)
    checks += 1
    assert pow(Q, 1, 2) == 1 and pow(G, Q, P) == 1
    checks += 1
    print("toycrypto self-test: OK (%d checks)" % checks)


if __name__ == "__main__":
    _selftest()
