#!/usr/bin/env python3
# ec-small-key-check.py: flag EC public keys whose private key is tiny.
#
# Walks G, 2G, 3G, ... up to --max and reports any certificate, CSR or
# public key whose point matches, i.e. private key d (or n - d) <= --max.
# The eMudhra intermediates of October 2026 had d < 256.
#
#   pip install cryptography
#   python3 ec-small-key-check.py [--max N] FILE.pem [FILE.pem ...]
#
# Exit status: 0 all clean, 1 weak key found, 2 nothing to check.
# https://dotstarsystems.com/blog/emudhra-ca-private-key-was-4/
import argparse
import re
import sys

from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec

# NIST prime curves: (p, a, Gx, Gy)
CURVES = {
    "secp256r1": (
        0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF,
        -3,
        0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
        0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5,
    ),
    "secp384r1": (
        2**384 - 2**128 - 2**96 + 2**32 - 1,
        -3,
        0xAA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7,
        0x3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F,
    ),
    "secp521r1": (
        2**521 - 1,
        -3,
        0x00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66,
        0x011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650,
    ),
}

PEM_RE = re.compile(rb"-----BEGIN ([A-Z ]+)-----.+?-----END \1-----", re.S)


def load_keys(path):
    """Yield (label, EllipticCurvePublicKey) for every EC key in a PEM file."""
    data = open(path, "rb").read()
    for i, m in enumerate(PEM_RE.finditer(data)):
        kind, blob = m.group(1), m.group(0)
        try:
            if kind == b"CERTIFICATE":
                obj = x509.load_pem_x509_certificate(blob)
                name, key = obj.subject.rfc4514_string(), obj.public_key()
            elif kind in (b"CERTIFICATE REQUEST", b"NEW CERTIFICATE REQUEST"):
                obj = x509.load_pem_x509_csr(blob)
                name, key = "CSR " + obj.subject.rfc4514_string(), obj.public_key()
            elif kind == b"PUBLIC KEY":
                name, key = "public key", serialization.load_pem_public_key(blob)
            else:
                continue
        except ValueError as e:
            print(f"{path}[{i}]: skipped: {e}", file=sys.stderr)
            continue
        if isinstance(key, ec.EllipticCurvePublicKey):
            yield f"{path}[{i}] {name}", key


def scan(curve, targets, limit):
    """Walk k*G for k = 1..limit; return {x: k} for matching x-coordinates.

    Matching on x alone also catches d = n - k, since -kG = (x, -y).
    """
    p, a, x, y = CURVES[curve]
    gx, gy, hits = x, y, {}
    for k in range(1, limit + 1):
        if x in targets:
            hits[x] = k
            if len(hits) == len(targets):
                break
        # affine addition (x, y) + G; doubling only at k = 1
        if x == gx:
            lam = (3 * x * x + a) * pow(2 * y, -1, p) % p
        else:
            lam = (gy - y) * pow(gx - x, -1, p) % p
        x, y = (nx := (lam * lam - x - gx) % p), (lam * (x - nx) - y) % p
    return hits


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--max", type=int, default=1 << 16,
                    help="largest private key to test (default 65536)")
    ap.add_argument("files", nargs="+")
    args = ap.parse_args()

    by_curve = {}
    for path in args.files:
        for label, key in load_keys(path):
            if key.curve.name not in CURVES:
                print(f"{label}: {key.curve.name} not supported, skipped", file=sys.stderr)
                continue
            by_curve.setdefault(key.curve.name, []).append((label, key.public_numbers().x))
    if not by_curve:
        print("no EC keys found", file=sys.stderr)
        return 2

    weak = 0
    for curve, keys in by_curve.items():
        hits = scan(curve, {x for _, x in keys}, args.max)
        for label, x in keys:
            if x in hits:
                weak += 1
                print(f"WEAK  {label}: d = {hits[x]} (or n - {hits[x]}), {curve}")
            else:
                print(f"ok    {label}: d > {args.max}, {curve}")
    return 1 if weak else 0


if __name__ == "__main__":
    sys.exit(main())
