Skip to main content

logicaffeine_proof/
factor.rs

1//! Structural factoring: the AIT thesis applied to public-key crypto.
2//!
3//! The compressibility ladder crushes symmetric keystreams by finding their *structure* — a short
4//! feedback register, a correlation, a low-degree annihilator. RSA lives in a different universe: its
5//! security is integer factorization of `N = p·q`, not sequence structure. But the same thesis governs
6//! it. A *weak* RSA modulus is one with exploitable STRUCTURE, and every classical factoring attack is a
7//! structure-detector: a small factor, primes that sit too close, a smooth `p−1`, a shared prime across
8//! moduli, a small private exponent. Each such structure is a compression — a short description of the
9//! secret — and each attack returns a re-checkable WITNESS (the factors themselves, `p·q = N`).
10//!
11//! The point of building the whole arsenal is the *ceiling*: run every structural attack against a
12//! soundly-generated modulus — two large, independent, well-separated strong primes — and it finds
13//! NOTHING within budget. RSA's safety is precisely that its modulus is the number-theoretic
14//! incompressible residue: no structural shortcut exists, and only the general (sub-)exponential
15//! algorithms remain, which real key sizes push out of reach. Crush every structured form; the sound
16//! form stands. That standing IS the proof.
17
18use logicaffeine_base::numeric::{BigInt, Rational};
19
20/// The Miller–Rabin witness bases (the first twelve primes) — deterministic for the modulus sizes used
21/// here, and overwhelmingly reliable beyond them.
22const MR_BASES: &[u64] = &[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
23
24fn one() -> BigInt {
25    BigInt::from_i64(1)
26}
27
28fn two() -> BigInt {
29    BigInt::from_i64(2)
30}
31
32/// `a mod m` for non-negative `a`, `m > 0`.
33fn rem(a: &BigInt, m: &BigInt) -> BigInt {
34    a.div_rem(m).expect("modulus is nonzero").1
35}
36
37/// The greatest common divisor of `|a|` and `|b|` (Euclid).
38pub fn gcd(a: &BigInt, b: &BigInt) -> BigInt {
39    let (mut a, mut b) = (a.abs(), b.abs());
40    while !b.is_zero() {
41        let r = rem(&a, &b);
42        a = b;
43        b = r;
44    }
45    a
46}
47
48/// The modular inverse `a⁻¹ mod m` via the extended Euclidean algorithm, or `None` if `gcd(a, m) ≠ 1`.
49pub fn mod_inverse(a: &BigInt, m: &BigInt) -> Option<BigInt> {
50    let (mut old_r, mut r) = (rem(a, m), m.clone());
51    let (mut old_s, mut s) = (one(), BigInt::zero());
52    while !r.is_zero() {
53        let (q, rr) = old_r.div_rem(&r).expect("nonzero");
54        old_r = r;
55        r = rr;
56        let ns = old_s.sub(&q.mul(&s));
57        old_s = s;
58        s = ns;
59    }
60    if old_r != one() {
61        return None;
62    }
63    let mut res = rem(&old_s, m);
64    if res.is_negative() {
65        res = res.add(m);
66    }
67    Some(res)
68}
69
70/// Modular exponentiation `base^exp mod m` with a full `BigInt` exponent (square-and-multiply, the
71/// exponent's bits read off by repeated halving).
72pub fn modpow(base: &BigInt, exp: &BigInt, m: &BigInt) -> BigInt {
73    if *m == one() {
74        return BigInt::zero();
75    }
76    let two = two();
77    let mut result = one();
78    let mut b = rem(base, m);
79    let mut e = exp.clone();
80    while !e.is_zero() {
81        let (q, bit) = e.div_rem(&two).expect("nonzero");
82        if !bit.is_zero() {
83            result = rem(&result.mul(&b), m);
84        }
85        b = rem(&b.mul(&b), m);
86        e = q;
87    }
88    result
89}
90
91/// The integer square root `⌊√n⌋` (Newton's method). The floating-point seed is only ~15 digits precise,
92/// so it is first forced to an OVERESTIMATE (`x² ≥ n`, a handful of doublings); from above, the Newton
93/// iteration `x ← ⌊(x + ⌊n/x⌋)/2⌋` decreases monotonically and halts exactly at `⌊√n⌋`.
94pub fn isqrt(n: &BigInt) -> BigInt {
95    if n.is_zero() || n.is_negative() {
96        return BigInt::zero();
97    }
98    let two = two();
99    let approx = n.to_f64().sqrt();
100    let mut x = if approx.is_finite() && approx >= 1.0 {
101        BigInt::parse_decimal(&format!("{approx:.0}")).unwrap_or_else(one)
102    } else {
103        one()
104    };
105    if x.is_zero() {
106        x = one();
107    }
108    while x.mul(&x) < *n {
109        x = x.mul(&two); // force an overestimate (the f64 seed may undershoot by ~10¹⁵)
110    }
111    loop {
112        let (q, _) = n.div_rem(&x).expect("nonzero");
113        let y = x.add(&q).div_rem(&two).expect("nonzero").0;
114        if y >= x {
115            return x;
116        }
117        x = y;
118    }
119}
120
121/// Miller–Rabin primality over `MR_BASES`.
122pub fn is_probable_prime(n: &BigInt) -> bool {
123    let (one, two) = (one(), two());
124    if *n < two {
125        return false;
126    }
127    if *n == two {
128        return true;
129    }
130    if !n.is_odd() {
131        return false;
132    }
133    // n − 1 = d·2ˢ.
134    let n1 = n.sub(&one);
135    let mut d = n1.clone();
136    let mut s = 0u32;
137    while !d.is_odd() {
138        d = d.div_rem(&two).expect("nonzero").0;
139        s += 1;
140    }
141    'base: for &a in MR_BASES {
142        let a = BigInt::from_u64(a);
143        if rem(&a, n).is_zero() {
144            continue; // a ≡ 0 mod n (n divides the base) — uninformative
145        }
146        let mut x = modpow(&a, &d, n);
147        if x == one || x == n1 {
148            continue;
149        }
150        for _ in 0..s.saturating_sub(1) {
151            x = rem(&x.mul(&x), n);
152            if x == n1 {
153                continue 'base;
154            }
155        }
156        return false;
157    }
158    true
159}
160
161/// The smallest prime `≥ start`.
162pub fn next_prime(start: &BigInt) -> BigInt {
163    let (one, two) = (one(), two());
164    if *start <= two {
165        return two;
166    }
167    let mut c = if start.is_odd() {
168        start.clone()
169    } else {
170        start.add(&one)
171    };
172    loop {
173        if is_probable_prime(&c) {
174            return c;
175        }
176        c = c.add(&two);
177    }
178}
179
180/// A nontrivial factorization `p·q = n` (`1 < p, q < n`) — the re-checkable witness every attack returns.
181pub fn verify_factorization(n: &BigInt, p: &BigInt, q: &BigInt) -> bool {
182    let one = one();
183    p.mul(q) == *n && *p > one && *q > one && *p < *n && *q < *n
184}
185
186fn split(n: &BigInt, d: &BigInt) -> Option<(BigInt, BigInt)> {
187    let one = one();
188    if *d > one && *d < *n {
189        let (q, r) = n.div_rem(d).expect("nonzero");
190        if r.is_zero() {
191            return Some((d.clone(), q));
192        }
193    }
194    None
195}
196
197/// Trial division up to `limit`: catches a **small factor** — a modulus that leaked a tiny prime.
198pub fn trial_division(n: &BigInt, limit: u64) -> Option<(BigInt, BigInt)> {
199    let mut d = 2u64;
200    while d <= limit {
201        let bd = BigInt::from_u64(d);
202        if bd.mul(&bd) > *n {
203            break;
204        }
205        if let Some(f) = split(n, &bd) {
206            return Some(f);
207        }
208        d += if d == 2 { 1 } else { 2 };
209    }
210    None
211}
212
213/// Fermat's method: catches **primes that sit too close** — `N = a² − b²` with `a` just above `√N`, so a
214/// few steps expose `(a−b, a+b)`. Structurally, close primes are a compressed key (one prime nearly fixes
215/// the other).
216pub fn fermat(n: &BigInt, max_iters: u64) -> Option<(BigInt, BigInt)> {
217    if !n.is_odd() {
218        return split(n, &two());
219    }
220    let one = one();
221    let mut a = isqrt(n);
222    if a.mul(&a) < *n {
223        a = a.add(&one);
224    }
225    for _ in 0..max_iters {
226        let b2 = a.mul(&a).sub(n);
227        let b = isqrt(&b2);
228        if b.mul(&b) == b2 {
229            let p = a.sub(&b);
230            let q = a.add(&b);
231            if verify_factorization(n, &p, &q) {
232                return Some((p, q));
233            }
234        }
235        a = a.add(&one);
236    }
237    None
238}
239
240/// Pollard's rho (`f(x) = x² + 1`, Floyd cycle detection): the general-purpose structural probe. Expected
241/// `O(N^{1/4})`, so it crushes moderate semiprimes but is bounded out on a large sound modulus.
242pub fn pollard_rho(n: &BigInt, max_iters: u64) -> Option<(BigInt, BigInt)> {
243    let (one, two) = (one(), two());
244    if !n.is_odd() {
245        return split(n, &two);
246    }
247    let f = |x: &BigInt| rem(&x.mul(x).add(&one), n);
248    let (mut x, mut y, mut d) = (two.clone(), two.clone(), one.clone());
249    let mut iters = 0u64;
250    while d == one && iters < max_iters {
251        x = f(&x);
252        y = f(&f(&y));
253        d = gcd(&x.sub(&y).abs(), n);
254        iters += 1;
255    }
256    split(n, &d)
257}
258
259/// Pollard's `p − 1`: catches a prime with a **smooth `p − 1`**. Raising a base to `B!` collapses to `1`
260/// modulo any prime whose `p − 1` is `B`-smooth, and `gcd(a − 1, N)` exposes it — the smoothness is the
261/// structure.
262pub fn pollard_p_minus_1(n: &BigInt, bound: u64) -> Option<(BigInt, BigInt)> {
263    let one = one();
264    let mut a = two();
265    for k in 2..=bound {
266        a = modpow(&a, &BigInt::from_u64(k), n);
267        if k % 16 == 0 || k == bound {
268            if let Some(f) = split(n, &gcd(&a.sub(&one), n)) {
269                return Some(f);
270            }
271        }
272    }
273    split(n, &gcd(&a.sub(&one), n))
274}
275
276/// Wiener's attack: catches a **small private exponent `d`** (`d < ⅓ N^{1/4}`). The convergents of the
277/// continued fraction of `e/N` include `k/d`; from `d` we recover `φ(N)`, then `p, q` as roots of
278/// `x² − (N − φ + 1)x + N`. A small `d` is a compressed private key — and this reuses the very
279/// continued-fraction / rational-reconstruction machinery the 2-adic FCSR rung was built on.
280pub fn wiener(e: &BigInt, n: &BigInt) -> Option<(BigInt, BigInt)> {
281    let (one, two, four) = (one(), two(), BigInt::from_i64(4));
282    let (mut num, mut den) = (e.clone(), n.clone());
283    // Convergent recurrence h_i / k_i (numerator = candidate multiplier k, denominator = candidate d).
284    let (mut h2, mut h1) = (BigInt::zero(), one.clone());
285    let (mut k2, mut k1) = (one.clone(), BigInt::zero());
286    for _ in 0..2000 {
287        if den.is_zero() {
288            break;
289        }
290        let (a, r) = num.div_rem(&den).expect("nonzero");
291        let h = a.mul(&h1).add(&h2); // candidate k (the small multiplier)
292        let k = a.mul(&k1).add(&k2); // candidate d (the private exponent)
293        if !h.is_zero() {
294            let (phi, prem) = e.mul(&k).sub(&one).div_rem(&h).expect("nonzero");
295            if prem.is_zero() {
296                // p, q are the roots of x² − (N − φ + 1)x + N.
297                let s = n.sub(&phi).add(&one); // p + q
298                let disc = s.mul(&s).sub(&four.mul(n));
299                if !disc.is_negative() {
300                    let sq = isqrt(&disc);
301                    if sq.mul(&sq) == disc {
302                        let p = s.sub(&sq).div_rem(&two).expect("nonzero").0;
303                        let q = s.add(&sq).div_rem(&two).expect("nonzero").0;
304                        if verify_factorization(n, &p, &q) {
305                            return Some((p, q));
306                        }
307                    }
308                }
309            }
310        }
311        num = den;
312        den = r;
313        (h2, h1) = (h1, h);
314        (k2, k1) = (k1, k);
315    }
316    None
317}
318
319// ---- Håstad broadcast: a MESSAGE-recovery lens (small public exponent + broadcast) ------------------
320//
321// Every attack above recovers the KEY. Håstad's recovers the MESSAGE, from a different structural
322// weakness: the same plaintext `m` sent to `k ≥ e` recipients under a small public exponent `e` and
323// distinct moduli. The ciphertexts are `cᵢ = mᵉ mod Nᵢ`, and since `m < Nᵢ` for all `i`, `mᵉ < ∏Nᵢ`.
324// The Chinese Remainder Theorem reconstructs `mᵉ mod ∏Nᵢ` — which, being smaller than the modulus, IS
325// `mᵉ` over the integers — and an integer `e`-th root pops out `m`. The plaintext is a low-complexity
326// object smeared across the broadcast; CRT gathers it back into a perfect power.
327
328fn pos_rem(a: &BigInt, m: &BigInt) -> BigInt {
329    let r = rem(a, m);
330    if r.is_negative() {
331        r.add(m)
332    } else {
333        r
334    }
335}
336
337/// Chinese Remainder Theorem: the unique `x` in `[0, ∏mᵢ)` with `x ≡ residuesᵢ (mod moduliᵢ)` for
338/// pairwise-coprime `moduli`, or `None` if a modular inverse fails (moduli not coprime).
339pub fn crt(residues: &[BigInt], moduli: &[BigInt]) -> Option<BigInt> {
340    if residues.is_empty() || residues.len() != moduli.len() {
341        return None;
342    }
343    let mut x = pos_rem(&residues[0], &moduli[0]);
344    let mut m = moduli[0].clone();
345    for i in 1..moduli.len() {
346        let mi = &moduli[i];
347        let inv = mod_inverse(&pos_rem(&m, mi), mi)?;
348        let diff = pos_rem(&residues[i].sub(&x), mi);
349        let t = pos_rem(&diff.mul(&inv), mi);
350        x = x.add(&m.mul(&t));
351        m = m.mul(mi);
352        x = pos_rem(&x, &m);
353    }
354    Some(x)
355}
356
357/// The integer `n`-th root `⌊x^{1/n}⌋` (Newton's method, overestimate seed then monotone descent, exact
358/// final adjustment — the `n`-th-root analogue of [`isqrt`]).
359pub fn integer_nth_root(x: &BigInt, n: u32) -> BigInt {
360    if n == 0 || x.is_negative() {
361        return BigInt::zero();
362    }
363    if n == 1 || x.is_zero() {
364        return x.clone();
365    }
366    let (one, two) = (one(), two());
367    let nn = BigInt::from_u64(n as u64);
368    let nm1 = BigInt::from_u64((n - 1) as u64);
369    let approx = x.to_f64().powf(1.0 / n as f64);
370    let mut r = if approx.is_finite() && approx >= 1.0 {
371        BigInt::parse_decimal(&format!("{approx:.0}")).unwrap_or_else(|| one.clone())
372    } else {
373        one.clone()
374    };
375    if r.is_zero() {
376        r = one.clone();
377    }
378    while r.pow(n) < *x {
379        r = r.mul(&two); // force an overestimate
380    }
381    loop {
382        let (q, _) = x.div_rem(&r.pow(n - 1)).expect("nonzero");
383        let next = nm1.mul(&r).add(&q).div_rem(&nn).expect("nonzero").0;
384        if next >= r {
385            break;
386        }
387        r = next;
388    }
389    while r.pow(n) > *x {
390        r = r.sub(&one);
391    }
392    while r.add(&one).pow(n) <= *x {
393        r = r.add(&one);
394    }
395    r
396}
397
398/// Håstad's broadcast attack: recover the plaintext `m` from `k ≥ e` ciphertexts `cᵢ = mᵉ mod Nᵢ` of the
399/// SAME message under a small public exponent `e` and distinct moduli (see the module note above). CRT
400/// reconstructs `mᵉ` exactly, and its integer `e`-th root is `m`. Returns the recovered message, or `None`
401/// if the CRT fails or the result is not a perfect `e`-th power (the precondition `k ≥ e` did not hold).
402pub fn hastad_broadcast_attack(
403    e: u32,
404    ciphertexts: &[BigInt],
405    moduli: &[BigInt],
406) -> Option<BigInt> {
407    if (ciphertexts.len() as u32) < e {
408        return None;
409    }
410    let c = crt(ciphertexts, moduli)?;
411    let m = integer_nth_root(&c, e);
412    (m.pow(e) == c).then_some(m)
413}
414
415// ---- More message-recovery lenses: common modulus, Franklin–Reiter, low-exponent --------------------
416
417/// Extended Euclid: `(g, x, y)` with `x·a + y·b = g = gcd(a, b)`.
418fn ext_gcd(a: &BigInt, b: &BigInt) -> (BigInt, BigInt, BigInt) {
419    let (mut old_r, mut r) = (a.clone(), b.clone());
420    let (mut old_s, mut s) = (one(), BigInt::zero());
421    let (mut old_t, mut t) = (BigInt::zero(), one());
422    while !r.is_zero() {
423        let (q, _) = old_r.div_rem(&r).expect("nonzero");
424        let nr = old_r.sub(&q.mul(&r));
425        old_r = r;
426        r = nr;
427        let ns = old_s.sub(&q.mul(&s));
428        old_s = s;
429        s = ns;
430        let nt = old_t.sub(&q.mul(&t));
431        old_t = t;
432        t = nt;
433    }
434    (old_r, old_s, old_t)
435}
436
437/// Common-modulus attack: recover `m` when the SAME message is sent to the same modulus `N` under two
438/// coprime public exponents `e₁, e₂` (a key-reuse mistake). Bézout gives `a·e₁ + b·e₂ = 1`, so
439/// `c₁ᵃ · c₂ᵇ = m^{a·e₁ + b·e₂} = m (mod N)` — negative exponents handled by inverting the ciphertext.
440pub fn common_modulus_attack(
441    e1: &BigInt,
442    e2: &BigInt,
443    c1: &BigInt,
444    c2: &BigInt,
445    n: &BigInt,
446) -> Option<BigInt> {
447    let (g, a, b) = ext_gcd(e1, e2);
448    if g != one() {
449        return None;
450    }
451    let t1 = if a.is_negative() {
452        modpow(&mod_inverse(c1, n)?, &a.negated(), n)
453    } else {
454        modpow(c1, &a, n)
455    };
456    let t2 = if b.is_negative() {
457        modpow(&mod_inverse(c2, n)?, &b.negated(), n)
458    } else {
459        modpow(c2, &b, n)
460    };
461    Some(rem(&t1.mul(&t2), n))
462}
463
464/// Low-exponent / no-padding attack: if `mᵉ < N` (a small message under a small public exponent with no
465/// padding), then `c = mᵉ` over the integers, so the plaintext is just the integer `e`-th root of `c`.
466pub fn low_exponent_message(c: &BigInt, e: u32) -> Option<BigInt> {
467    let m = integer_nth_root(c, e);
468    (m.pow(e) == *c).then_some(m)
469}
470
471fn poly_norm_mod(p: &[BigInt], n: &BigInt) -> Vec<BigInt> {
472    let mut v: Vec<BigInt> = p.iter().map(|c| pos_rem(c, n)).collect();
473    while v.len() > 1 && v.last().is_some_and(|c| c.is_zero()) {
474        v.pop();
475    }
476    if v.is_empty() {
477        v.push(BigInt::zero());
478    }
479    v
480}
481
482fn poly_mul_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Vec<BigInt> {
483    let mut out = vec![BigInt::zero(); a.len() + b.len() - 1];
484    for (i, ai) in a.iter().enumerate() {
485        for (j, bj) in b.iter().enumerate() {
486            out[i + j] = pos_rem(&out[i + j].add(&ai.mul(bj)), n);
487        }
488    }
489    poly_norm_mod(&out, n)
490}
491
492/// Remainder of `a` divided by `b` in `(ℤ/N)[x]` (long division, leading coefficient of `b` inverted mod
493/// `N`). `None` if that inverse fails — which would itself expose a factor of `N`.
494fn poly_rem_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Option<Vec<BigInt>> {
495    let b = poly_norm_mod(b, n);
496    let db = b.len() - 1;
497    if b.iter().all(|c| c.is_zero()) {
498        return None;
499    }
500    let lead_inv = mod_inverse(&b[db], n)?;
501    let mut r = poly_norm_mod(a, n);
502    while r.len() > db {
503        let dr = r.len() - 1;
504        let factor = pos_rem(&r[dr].mul(&lead_inv), n);
505        let shift = dr - db;
506        for i in 0..b.len() {
507            r[shift + i] = pos_rem(&r[shift + i].sub(&factor.mul(&b[i])), n);
508        }
509        r = poly_norm_mod(&r, n);
510    }
511    Some(r)
512}
513
514/// Monic GCD of two polynomials over `(ℤ/N)[x]` (Euclidean algorithm).
515fn poly_gcd_mod(a: &[BigInt], b: &[BigInt], n: &BigInt) -> Option<Vec<BigInt>> {
516    let mut a = poly_norm_mod(a, n);
517    let mut b = poly_norm_mod(b, n);
518    while !(b.len() == 1 && b[0].is_zero()) {
519        let r = poly_rem_mod(&a, &b, n)?;
520        a = b;
521        b = r;
522    }
523    Some(a)
524}
525
526/// Franklin–Reiter related-message attack: recover `m` from ciphertexts of two LINEARLY RELATED messages
527/// `m` and `m + r` (known `r`) under the same modulus `N` and a small public exponent `e`. Both
528/// `g₁(x) = xᵉ − c₁` and `g₂(x) = (x + r)ᵉ − c₂` have the root `x = m mod N`, so their GCD over `(ℤ/N)[x]`
529/// is the linear factor `x − m`, and `m` is read straight off it. The lens: two ciphertexts sharing a
530/// hidden root, extracted by polynomial GCD.
531pub fn franklin_reiter_attack(
532    e: u32,
533    r: &BigInt,
534    c1: &BigInt,
535    c2: &BigInt,
536    n: &BigInt,
537) -> Option<BigInt> {
538    let mut g1 = vec![BigInt::zero(); (e + 1) as usize];
539    g1[0] = pos_rem(&c1.negated(), n);
540    g1[e as usize] = one();
541
542    let xr = vec![pos_rem(r, n), one()];
543    let mut g2 = vec![one()];
544    for _ in 0..e {
545        g2 = poly_mul_mod(&g2, &xr, n);
546    }
547    g2[0] = pos_rem(&g2[0].sub(c2), n);
548
549    let g = poly_gcd_mod(&g1, &g2, n)?;
550    if g.len() == 2 {
551        let m = pos_rem(&g[0].negated().mul(&mod_inverse(&g[1], n)?), n);
552        if modpow(&m, &BigInt::from_u64(e as u64), n) == pos_rem(c1, n) {
553            return Some(m);
554        }
555    }
556    None
557}
558
559// ---- Coppersmith's method: the LATTICE lens on RSA (a break with no factoring shortcut) --------------
560//
561// Polynomial arithmetic over the integers (coefficients low-to-high; `p[k]` = coefficient of `xᵏ`).
562
563fn poly_mul(a: &[BigInt], b: &[BigInt]) -> Vec<BigInt> {
564    if a.is_empty() || b.is_empty() {
565        return Vec::new();
566    }
567    let mut out = vec![BigInt::zero(); a.len() + b.len() - 1];
568    for (i, ai) in a.iter().enumerate() {
569        for (j, bj) in b.iter().enumerate() {
570            out[i + j] = out[i + j].add(&ai.mul(bj));
571        }
572    }
573    out
574}
575
576fn poly_pow(base: &[BigInt], e: usize) -> Vec<BigInt> {
577    let mut acc = vec![one()];
578    for _ in 0..e {
579        acc = poly_mul(&acc, base);
580    }
581    acc
582}
583
584fn poly_eval(coeffs: &[BigInt], x: &BigInt) -> BigInt {
585    coeffs
586        .iter()
587        .rev()
588        .fold(BigInt::zero(), |acc, c| acc.mul(x).add(c))
589}
590
591/// Find an integer root of `coeffs` in `[0, bound]`, if one exists: a floating-point Newton search
592/// (coefficients normalized to keep the doubles finite) proposes candidates, each verified EXACTLY with
593/// `BigInt` evaluation. Root-finding is the easy step — the miracle is that Coppersmith's lattice produced
594/// a polynomial whose small root is an *integer* root at all.
595fn poly_integer_root(coeffs: &[BigInt], bound: &BigInt) -> Option<BigInt> {
596    let maxc = coeffs.iter().map(|c| c.abs()).max()?;
597    if maxc.is_zero() {
598        return None;
599    }
600    // For a small bound, scan exactly — the root of the recovered polynomial is trivial to locate once
601    // the lattice has produced it (this is post-processing, not the attack). Larger bounds fall through
602    // to the Newton search below (as every Coppersmith implementation does).
603    if bound.to_f64() <= 4_200_000.0 {
604        let mut x = BigInt::zero();
605        let one = one();
606        while x <= *bound {
607            if poly_eval(coeffs, &x).is_zero() {
608                return Some(x);
609            }
610            x = x.add(&one);
611        }
612        return None;
613    }
614    let cf: Vec<f64> = coeffs
615        .iter()
616        .map(|c| {
617            Rational::new(c.clone(), maxc.clone())
618                .map(|r| r.to_f64())
619                .unwrap_or(0.0)
620        })
621        .collect();
622    let eval = |x: f64| cf.iter().rev().fold(0.0, |acc, &c| acc * x + c);
623    let deriv = |x: f64| {
624        (1..cf.len())
625            .rev()
626            .fold(0.0, |acc, k| acc * x + cf[k] * k as f64)
627    };
628    let bound_f = bound.to_f64();
629
630    let mut seeds: Vec<f64> = Vec::new();
631    let mut p = 1.0;
632    while p <= bound_f {
633        seeds.push(p);
634        p *= 1.5;
635    }
636    for i in 0..=64 {
637        seeds.push(bound_f * i as f64 / 64.0);
638    }
639
640    let mut seen: Vec<BigInt> = Vec::new();
641    for &s in &seeds {
642        let mut x = s;
643        for _ in 0..200 {
644            let d = deriv(x);
645            if d.abs() < 1e-15 {
646                break;
647            }
648            let nx = x - eval(x) / d;
649            if !nx.is_finite() {
650                break;
651            }
652            if (nx - x).abs() < 0.4 {
653                x = nx;
654                break;
655            }
656            x = nx;
657        }
658        if x.is_finite() && x >= -1.0 && x <= bound_f + 1.0 {
659            if let Some(cand) = BigInt::parse_decimal(&format!("{:.0}", x.max(0.0))) {
660                if !seen.contains(&cand) {
661                    if cand <= *bound && poly_eval(coeffs, &cand).is_zero() {
662                        return Some(cand);
663                    }
664                    seen.push(cand);
665                }
666            }
667        }
668    }
669    None
670}
671
672fn poly_derivative(p: &[BigInt]) -> Vec<BigInt> {
673    (1..p.len())
674        .map(|k| p[k].mul(&BigInt::from_i64(k as i64)))
675        .collect()
676}
677
678/// Nearest integer to `a/b` (ties away from zero).
679fn round_div_factor(a: &BigInt, b: &BigInt) -> BigInt {
680    let (q, r) = a.div_rem(b).expect("nonzero");
681    if r.is_zero() {
682        return q;
683    }
684    if BigInt::from_i64(2).mul(&r.abs()) > b.abs() {
685        if a.is_negative() ^ b.is_negative() {
686            q.sub(&one())
687        } else {
688            q.add(&one())
689        }
690    } else {
691        q
692    }
693}
694
695/// Exact integer roots of `res` in `[−bound, bound]`: a floating-point Newton pass proposes seeds, and
696/// EXACT integer Newton (`x ← x − round(res(x)/res'(x))`, evaluated in `BigInt`) refines each to a true
697/// integer root — necessary because the resultant's coefficients are far too large for f64 to locate the
698/// root directly.
699fn integer_roots_of(res: &[BigInt], bound: &BigInt) -> Vec<BigInt> {
700    let deriv = poly_derivative(res);
701    let mut out: Vec<BigInt> = Vec::new();
702    for seed in real_root_candidates(res, bound) {
703        let mut x = seed;
704        for _ in 0..80 {
705            let fx = poly_eval(res, &x);
706            if fx.is_zero() {
707                break;
708            }
709            let dfx = poly_eval(&deriv, &x);
710            if dfx.is_zero() {
711                break;
712            }
713            let step = round_div_factor(&fx, &dfx);
714            if step.is_zero() {
715                break;
716            }
717            x = x.sub(&step);
718        }
719        if poly_eval(res, &x).is_zero() && x.abs() <= *bound && !out.contains(&x) {
720            out.push(x);
721        }
722    }
723    out
724}
725
726/// Factor `N` from the **high bits of one prime** (Coppersmith's method). We know `p = p_high + x₀` with
727/// `0 ≤ x₀ < 2^unknown_bits`; the monic linear polynomial `f(x) = x + p_high` has the small root `x₀`
728/// modulo the unknown factor `p`. Coppersmith builds a lattice from the `N`-power and `x`-shift multiples
729/// of `f` (all vanishing modulo `pᵐ` at `x₀`), LLL-reduces it, and reads a short vector whose small root
730/// is an INTEGER root of a real polynomial — recovering `x₀`, hence `p`. This is the LATTICE lens: a
731/// factorization from PARTIAL knowledge that no factoring shortcut (Fermat, rho, `p−1`) can provide.
732pub fn coppersmith_factor_high_bits(
733    n: &BigInt,
734    p_high: &BigInt,
735    unknown_bits: u32,
736) -> Option<(BigInt, BigInt)> {
737    let two = two();
738    let mut x_bound = one();
739    for _ in 0..unknown_bits {
740        x_bound = x_bound.mul(&two);
741    }
742    // A larger lattice pushes `unknown_bits` toward the N^{1/4} limit. The float-Gram-Schmidt LLL
743    // (`lll_reduce_bigint`) handles this dimension in milliseconds — the exact-rational version could not.
744    let (m, t) = (4usize, 4usize);
745    let deg = m + t;
746    let f = vec![p_high.clone(), one()]; // f(x) = p_high + x
747
748    // Polynomials that vanish modulo pᵐ at x₀: gᵢ = N^{m-i}·fⁱ (i=0..m) and hⱼ = xʲ·fᵐ (j=1..t).
749    let mut polys: Vec<Vec<BigInt>> = Vec::new();
750    for i in 0..=m {
751        let scale = n.pow((m - i) as u32);
752        polys.push(poly_pow(&f, i).iter().map(|c| c.mul(&scale)).collect());
753    }
754    let fm = poly_pow(&f, m);
755    for j in 1..=t {
756        let mut p = vec![BigInt::zero(); j];
757        p.extend_from_slice(&fm);
758        polys.push(p);
759    }
760
761    // Lattice rows: coefficient k scaled by Xᵏ (so a short row ⇒ a small-normed polynomial in x·X).
762    let mut xpow = vec![one()];
763    for k in 1..=deg {
764        xpow.push(xpow[k - 1].mul(&x_bound));
765    }
766    let rows: Vec<Vec<BigInt>> = polys
767        .iter()
768        .map(|p| {
769            (0..=deg)
770                .map(|k| p.get(k).cloned().unwrap_or_else(BigInt::zero).mul(&xpow[k]))
771                .collect()
772        })
773        .collect();
774
775    let reduced = crate::lattice::lll_reduce_bigint_fp(&rows);
776    for row in &reduced {
777        // Unscale: hₖ = rowₖ / Xᵏ (exact — every lattice entry is an integer multiple of Xᵏ).
778        let mut h = Vec::with_capacity(deg + 1);
779        let mut ok = true;
780        for k in 0..=deg {
781            let (q, r) = row[k].div_rem(&xpow[k]).expect("nonzero");
782            if !r.is_zero() {
783                ok = false;
784                break;
785            }
786            h.push(q);
787        }
788        if !ok || h.iter().all(|c| c.is_zero()) {
789            continue;
790        }
791        if let Some(x0) = poly_integer_root(&h, &x_bound) {
792            if let Some(f) = split(n, &p_high.add(&x0)) {
793                return Some(f);
794            }
795        }
796    }
797    None
798}
799
800/// Derive the RSA private exponent `d = e⁻¹ mod φ(N)` from the public exponent and the two primes
801/// (`φ = (p−1)(q−1)`), or `None` if `e` is not coprime to `φ`. The "if you can factor, you can break RSA"
802/// direction: the factorization hands over the private key.
803pub fn rsa_private_exponent(e: &BigInt, p: &BigInt, q: &BigInt) -> Option<BigInt> {
804    let one = one();
805    mod_inverse(e, &p.sub(&one).mul(&q.sub(&one)))
806}
807
808/// Factor `N` from the RSA private exponent `d` (Miller's deterministic reduction). Since `e·d − 1` is a
809/// multiple of `λ(N)`, writing it as `t·2ˢ` and raising a base `g` to `t·2ⁱ` walks a chain that ends at
810/// `1`; a step where the value squares to `1` while itself being `≠ ±1` is a NONTRIVIAL square root of
811/// unity, and `gcd(x − 1, N)` splits `N`. This is the converse of [`rsa_private_exponent`]: it proves
812/// that recovering the private key is **computationally equivalent to factoring the modulus** — the two
813/// are one problem, so RSA breaks exactly when `N` factors. Returns `(p, q)` or `None` (no base worked).
814pub fn factor_via_private_exponent(n: &BigInt, e: &BigInt, d: &BigInt) -> Option<(BigInt, BigInt)> {
815    let (one, two) = (one(), two());
816    let n1 = n.sub(&one);
817    let k = e.mul(d).sub(&one);
818    if k.is_zero() || k.is_negative() {
819        return None;
820    }
821    // k = t·2ˢ, t odd.
822    let mut t = k;
823    let mut s = 0u32;
824    while !t.is_odd() {
825        t = t.div_rem(&two).expect("nonzero").0;
826        s += 1;
827    }
828    for &gb in MR_BASES {
829        let g = BigInt::from_u64(gb);
830        let shared = gcd(&g, n);
831        if shared != one {
832            if let Some(f) = split(n, &shared) {
833                return Some(f);
834            }
835            continue;
836        }
837        let mut x = modpow(&g, &t, n);
838        if x == one || x == n1 {
839            continue;
840        }
841        for _ in 0..s {
842            let y = modpow(&x, &two, n);
843            if y == one {
844                // x is a square root of 1 with x ∉ {1, N−1}: a nontrivial root splits N.
845                if let Some(f) = split(n, &gcd(&x.sub(&one), n)) {
846                    return Some(f);
847                }
848                break;
849            }
850            if y == n1 {
851                break; // x² ≡ −1: this base gives no nontrivial root
852            }
853            x = y;
854        }
855    }
856    None
857}
858
859/// Batch GCD: catches a **shared prime** reused across moduli — the classic failure of low-entropy key
860/// generation. Any pair with `gcd(Nᵢ, Nⱼ) > 1` hands over the common factor for free.
861pub fn batch_gcd(moduli: &[BigInt]) -> Vec<(usize, usize, BigInt)> {
862    let one = one();
863    let mut hits = Vec::new();
864    for i in 0..moduli.len() {
865        for j in (i + 1)..moduli.len() {
866            let g = gcd(&moduli[i], &moduli[j]);
867            if g > one {
868                hits.push((i, j, g));
869            }
870        }
871    }
872    hits
873}
874
875// ---- Dixon's method: RSA's ring structure broken by OUR GF(2) symmetry breaking -------------------
876//
877// The algebraic rungs (D, G, J) all turn on one primitive: finding a GF(2) linear DEPENDENCY — a subset
878// of vectors that XORs to zero. That same symmetry break factors integers. Dixon's method (the heart of
879// the quadratic sieve) collects numbers `r` whose square `r² mod N` is smooth over a small prime base,
880// records each as an exponent vector, and finds a subset whose product is a PERFECT SQUARE — which is
881// exactly a GF(2) kernel vector of the parity matrix. That yields `x² ≡ y² (mod N)`, and `gcd(x−y, N)`
882// splits `N`. It uses RSA's own ring structure (congruences of squares) and our own symmetry breaking
883// (the dependency search), so it breaks small and medium moduli; on a sound modulus it degrades to the
884// sub-exponential regime (the real quadratic-sieve / GNFS frontier) — the honest boundary.
885
886/// Every GF(2) linear dependency among `rows` (subsets of row indices that XOR to the zero vector), found
887/// by Gaussian elimination with identity tracking. This is the symmetry-break at the core of Dixon's
888/// method, shared with the algebraic rungs.
889fn gf2_dependencies(rows: &[Vec<bool>], ncols: usize) -> Vec<Vec<usize>> {
890    let m = rows.len();
891    let mut mat: Vec<(Vec<bool>, Vec<bool>)> = rows
892        .iter()
893        .enumerate()
894        .map(|(i, r)| {
895            let mut tag = vec![false; m];
896            tag[i] = true;
897            (r.clone(), tag)
898        })
899        .collect();
900    let mut pivot = 0;
901    for col in 0..ncols {
902        let Some(pr) = (pivot..m).find(|&i| mat[i].0[col]) else {
903            continue;
904        };
905        mat.swap(pivot, pr);
906        let (prow, ptag) = (mat[pivot].0.clone(), mat[pivot].1.clone());
907        for i in 0..m {
908            if i != pivot && mat[i].0[col] {
909                for c in 0..ncols {
910                    mat[i].0[c] ^= prow[c];
911                }
912                for c in 0..m {
913                    mat[i].1[c] ^= ptag[c];
914                }
915            }
916        }
917        pivot += 1;
918    }
919    mat.iter()
920        .filter(|(prim, _)| prim.iter().all(|&b| !b))
921        .map(|(_, tag)| (0..m).filter(|&i| tag[i]).collect())
922        .filter(|s: &Vec<usize>| !s.is_empty())
923        .collect()
924}
925
926/// Dixon's method: factor `N` via a congruence of squares found by a GF(2) dependency among smooth
927/// relations (see the module note above). Searches `r = ⌈√N⌉, ⌈√N⌉+1, …` for up to `tries` steps to
928/// gather relations whose `r² mod N` is smooth over `base`, then combines them. Returns `(p, q)` or
929/// `None` (not enough smooth relations found, or only trivial congruences). Reuses our GF(2)
930/// symmetry-breaking on RSA's ring structure.
931pub fn dixon_factor(n: &BigInt, base: &[u64], tries: usize) -> Option<(BigInt, BigInt)> {
932    let one = one();
933    let need = base.len() + 5;
934    let mut rels: Vec<(BigInt, Vec<u64>)> = Vec::new();
935    let mut r = isqrt(n).add(&one);
936    let mut steps = 0;
937    while rels.len() < need && steps < tries {
938        let mut s = rem(&r.mul(&r), n);
939        let mut exps = vec![0u64; base.len()];
940        for (bi, &b) in base.iter().enumerate() {
941            let bb = BigInt::from_u64(b);
942            while let Some((q, rr)) = s.div_rem(&bb) {
943                if rr.is_zero() {
944                    s = q;
945                    exps[bi] += 1;
946                } else {
947                    break;
948                }
949            }
950        }
951        if s == one {
952            rels.push((r.clone(), exps));
953        }
954        r = r.add(&one);
955        steps += 1;
956    }
957    if rels.len() < 2 {
958        return None;
959    }
960    let rows: Vec<Vec<bool>> = rels
961        .iter()
962        .map(|(_, e)| e.iter().map(|&x| x & 1 == 1).collect())
963        .collect();
964    for dep in gf2_dependencies(&rows, base.len()) {
965        let mut x = one.clone();
966        let mut total = vec![0u64; base.len()];
967        for &i in &dep {
968            x = rem(&x.mul(&rels[i].0), n);
969            for (k, &e) in rels[i].1.iter().enumerate() {
970                total[k] += e;
971            }
972        }
973        let mut y = one.clone();
974        for (k, &e) in total.iter().enumerate() {
975            y = rem(
976                &y.mul(&modpow(
977                    &BigInt::from_u64(base[k]),
978                    &BigInt::from_u64(e / 2),
979                    n,
980                )),
981                n,
982            );
983        }
984        let diff = if x >= y { x.sub(&y) } else { x.add(n).sub(&y) };
985        for cand in [gcd(&diff, n), gcd(&x.add(&y), n)] {
986            if let Some(f) = split(n, &cand) {
987                return Some(f);
988            }
989        }
990    }
991    None
992}
993
994// ---- Quadratic sieve: real sieving (the L[½] algorithm, GNFS's predecessor) ------------------------
995//
996// Dixon trial-divides `r² mod N` at every step; the quadratic sieve replaces that with a SIEVE. It uses
997// `Q(x) = (⌈√N⌉ + x)² − N`, small for small `x`, and for each factor-base prime `p` marks the interval
998// positions where `p | Q(x)` (the two roots of `Q ≡ 0 mod p`) by adding `ln p` to a running total. Where
999// that total reaches `ln|Q(x)|`, `Q(x)` is smooth — found without dividing. The smooth `Q(x)` become
1000// relations, and the SAME GF(2) dependency search factors `N`. This is sub-exponential (`L[½]`); its far
1001// deeper cousin GNFS is `L[⅓]` — still sub-exponential, so both confirm the wall rather than breaching it.
1002
1003fn is_small_prime(p: u64) -> bool {
1004    if p < 2 {
1005        return false;
1006    }
1007    let mut d = 2u64;
1008    while d * d <= p {
1009        if p % d == 0 {
1010            return false;
1011        }
1012        d += 1;
1013    }
1014    true
1015}
1016
1017fn bigint_mod_u64(n: &BigInt, p: u64) -> u64 {
1018    n.div_rem(&BigInt::from_u64(p))
1019        .expect("nonzero")
1020        .1
1021        .to_i64()
1022        .unwrap_or(0) as u64
1023}
1024
1025/// A square root of `a` modulo the small prime `p` (brute force — the factor-base primes are tiny), or
1026/// `None` if `a` is a non-residue.
1027fn modular_sqrt_u64(a: u64, p: u64) -> Option<u64> {
1028    let a = a % p;
1029    (0..p).find(|&r| (r as u128 * r as u128 % p as u128) as u64 == a)
1030}
1031
1032/// The quadratic sieve (see the module note above): factor `N` by log-sieving `Q(x) = (⌈√N⌉+x)² − N`
1033/// over `[0, m_interval)` against the factor base of primes `≤ b` for which `N` is a quadratic residue,
1034/// then combining smooth relations through a GF(2) dependency. Returns `(p, q)` or `None`.
1035pub fn quadratic_sieve(n: &BigInt, b: u64, m_interval: usize) -> Option<(BigInt, BigInt)> {
1036    let one = one();
1037    let a = isqrt(n).add(&one);
1038
1039    // Factor base: primes p ≤ b with N a quadratic residue mod p, and their two roots of Q ≡ 0 mod p.
1040    let mut base: Vec<u64> = Vec::new();
1041    let mut roots: Vec<(u64, u64)> = Vec::new();
1042    for p in 2..=b {
1043        if !is_small_prime(p) {
1044            continue;
1045        }
1046        let np = bigint_mod_u64(n, p);
1047        if p == 2 {
1048            base.push(2);
1049            roots.push((np % 2, np % 2));
1050        } else if let Some(r) = modular_sqrt_u64(np, p) {
1051            base.push(p);
1052            roots.push((r, p - r));
1053        }
1054    }
1055    if base.len() < 3 {
1056        return None;
1057    }
1058
1059    // Log-sieve the interval.
1060    let mut sieve = vec![0f64; m_interval];
1061    for (bi, &p) in base.iter().enumerate() {
1062        let am = bigint_mod_u64(&a, p) as i64;
1063        let (r1, r2) = roots[bi];
1064        let both = [r1, r2];
1065        let candidates: &[u64] = if p == 2 { &both[..1] } else { &both[..] };
1066        for &root in candidates {
1067            let mut x = ((root as i64 - am).rem_euclid(p as i64)) as usize;
1068            while x < m_interval {
1069                sieve[x] += (p as f64).ln();
1070                x += p as usize;
1071            }
1072        }
1073    }
1074
1075    // Collect smooth relations: sieve pinpoints candidates, exact trial division confirms them.
1076    let mut rels: Vec<(BigInt, Vec<u64>)> = Vec::new();
1077    for x in 0..m_interval {
1078        let ax = a.add(&BigInt::from_u64(x as u64));
1079        let q = ax.mul(&ax).sub(n);
1080        if q.is_zero() {
1081            continue;
1082        }
1083        // The sieve accounts for one ln(p) per distinct factor; require it to cover at least half the
1084        // log-mass of Q(x) (generous, so no smooth value is missed), then confirm by exact division.
1085        if sieve[x] < 0.5 * q.to_f64().ln() {
1086            continue;
1087        }
1088        let mut qq = q;
1089        let mut exps = vec![0u64; base.len()];
1090        for (bi, &p) in base.iter().enumerate() {
1091            let bp = BigInt::from_u64(p);
1092            while let Some((quo, rr)) = qq.div_rem(&bp) {
1093                if rr.is_zero() {
1094                    qq = quo;
1095                    exps[bi] += 1;
1096                } else {
1097                    break;
1098                }
1099            }
1100        }
1101        if qq == one {
1102            rels.push((ax, exps));
1103            if rels.len() > base.len() + 5 {
1104                break;
1105            }
1106        }
1107    }
1108    if rels.len() < 2 {
1109        return None;
1110    }
1111
1112    let rows: Vec<Vec<bool>> = rels
1113        .iter()
1114        .map(|(_, e)| e.iter().map(|&x| x & 1 == 1).collect())
1115        .collect();
1116    for dep in gf2_dependencies(&rows, base.len()) {
1117        let mut x = one.clone();
1118        let mut total = vec![0u64; base.len()];
1119        for &i in &dep {
1120            x = rem(&x.mul(&rels[i].0), n);
1121            for (k, &e) in rels[i].1.iter().enumerate() {
1122                total[k] += e;
1123            }
1124        }
1125        let mut y = one.clone();
1126        for (k, &e) in total.iter().enumerate() {
1127            y = rem(
1128                &y.mul(&modpow(
1129                    &BigInt::from_u64(base[k]),
1130                    &BigInt::from_u64(e / 2),
1131                    n,
1132                )),
1133                n,
1134            );
1135        }
1136        let diff = if x >= y { x.sub(&y) } else { x.add(n).sub(&y) };
1137        for cand in [gcd(&diff, n), gcd(&x.add(&y), n)] {
1138            if let Some(f) = split(n, &cand) {
1139                return Some(f);
1140            }
1141        }
1142    }
1143    None
1144}
1145
1146// ---- Resultants: eliminate a variable from two bivariate polynomials (Boneh–Durfee's core step) ------
1147//
1148// A bivariate polynomial is a map from monomial `(i, j)` (meaning `xⁱyʲ`) to its integer coefficient.
1149type BPoly = std::collections::BTreeMap<(u32, u32), BigInt>;
1150
1151/// The degree of a dense univariate polynomial (coefficients low-to-high), ignoring trailing zeros.
1152fn poly_deg(p: &[BigInt]) -> usize {
1153    let mut d = p.len();
1154    while d > 0 && p[d - 1].is_zero() {
1155        d -= 1;
1156    }
1157    d.saturating_sub(1)
1158}
1159
1160/// The determinant of an integer matrix by the fraction-free Bareiss algorithm — exact, no rationals.
1161fn det_bareiss(mut a: Vec<Vec<BigInt>>) -> BigInt {
1162    let n = a.len();
1163    if n == 0 {
1164        return one();
1165    }
1166    let mut prev = one();
1167    let mut neg = false;
1168    for k in 0..n - 1 {
1169        if a[k][k].is_zero() {
1170            match (k + 1..n).find(|&i| !a[i][k].is_zero()) {
1171                Some(p) => {
1172                    a.swap(k, p);
1173                    neg = !neg;
1174                }
1175                None => return BigInt::zero(),
1176            }
1177        }
1178        for i in k + 1..n {
1179            for j in k + 1..n {
1180                let num = a[i][j].mul(&a[k][k]).sub(&a[i][k].mul(&a[k][j]));
1181                a[i][j] = num.div_rem(&prev).expect("Bareiss division is exact").0;
1182            }
1183        }
1184        prev = a[k][k].clone();
1185    }
1186    if neg {
1187        a[n - 1][n - 1].negated()
1188    } else {
1189        a[n - 1][n - 1].clone()
1190    }
1191}
1192
1193/// The resultant of two univariate polynomials (coefficients low-to-high) — the Sylvester determinant.
1194fn univariate_resultant(a: &[BigInt], b: &[BigInt]) -> BigInt {
1195    let (da, db) = (poly_deg(a), poly_deg(b));
1196    if a.iter().all(|c| c.is_zero()) || b.iter().all(|c| c.is_zero()) {
1197        return BigInt::zero();
1198    }
1199    if da == 0 {
1200        return a[0].pow(db as u32);
1201    }
1202    if db == 0 {
1203        return b[0].pow(da as u32);
1204    }
1205    let n = da + db;
1206    let mut syl = vec![vec![BigInt::zero(); n]; n];
1207    for r in 0..db {
1208        for c in 0..=da {
1209            syl[r][r + c] = a[da - c].clone();
1210        }
1211    }
1212    for r in 0..da {
1213        for c in 0..=db {
1214            syl[db + r][r + c] = b[db - c].clone();
1215        }
1216    }
1217    det_bareiss(syl)
1218}
1219
1220/// Evaluate a bivariate polynomial at `y = t`, returning the univariate polynomial in `x` (low-to-high).
1221fn eval_bivar_at_y(g: &BPoly, t: &BigInt) -> Vec<BigInt> {
1222    let max_i = g.keys().map(|&(i, _)| i).max().unwrap_or(0) as usize;
1223    let mut uni = vec![BigInt::zero(); max_i + 1];
1224    for (&(i, j), c) in g {
1225        uni[i as usize] = uni[i as usize].add(&c.mul(&t.pow(j)));
1226    }
1227    uni
1228}
1229
1230/// Lagrange-interpolate the unique polynomial (coefficients low-to-high) through `points`.
1231fn lagrange_interpolate(points: &[(BigInt, BigInt)]) -> Vec<BigInt> {
1232    let n = points.len();
1233    let mut acc = vec![Rational::zero(); n];
1234    for (i, (xi, yi)) in points.iter().enumerate() {
1235        // Basis polynomial Lᵢ(x) = Π_{m≠i} (x − xₘ)/(xᵢ − xₘ), scaled by yᵢ.
1236        let mut basis = vec![Rational::zero(); n];
1237        basis[0] = Rational::from_bigint(yi.clone());
1238        let mut denom = Rational::from_i64(1);
1239        let mut deg = 0;
1240        for (m, (xm, _)) in points.iter().enumerate() {
1241            if m == i {
1242                continue;
1243            }
1244            // Multiply basis by (x − xₘ).
1245            for d in (0..=deg).rev() {
1246                let shifted = basis[d].clone();
1247                basis[d + 1] = basis[d + 1].add(&shifted);
1248                basis[d] = basis[d].mul(&Rational::from_bigint(xm.negated()));
1249            }
1250            deg += 1;
1251            denom = denom.mul(&Rational::from_bigint(xi.sub(xm)));
1252        }
1253        let inv = denom.recip().expect("distinct nodes");
1254        for d in 0..n {
1255            acc[d] = acc[d].add(&basis[d].mul(&inv));
1256        }
1257    }
1258    acc.iter().map(|r| r.round()).collect()
1259}
1260
1261/// Eliminate `x` from two bivariate polynomials: `Resₓ(g1, g2)`, a univariate polynomial in `y`
1262/// (coefficients low-to-high) whose roots include every shared `y`-coordinate. Computed by evaluating the
1263/// resultant at enough integer `y`-points and interpolating — avoiding a symbolic polynomial determinant.
1264fn bivariate_resultant_x(g1: &BPoly, g2: &BPoly) -> Vec<BigInt> {
1265    let dx = |g: &BPoly| g.keys().map(|&(i, _)| i).max().unwrap_or(0) as usize;
1266    let dy = |g: &BPoly| g.keys().map(|&(_, j)| j).max().unwrap_or(0) as usize;
1267    let degree = dx(g1) * dy(g2) + dx(g2) * dy(g1);
1268    let points: Vec<(BigInt, BigInt)> = (0..=degree as i64)
1269        .map(|t| {
1270            let ty = BigInt::from_i64(t);
1271            let r = univariate_resultant(&eval_bivar_at_y(g1, &ty), &eval_bivar_at_y(g2, &ty));
1272            (ty, r)
1273        })
1274        .collect();
1275    lagrange_interpolate(&points)
1276}
1277
1278fn bpoly_mul(a: &BPoly, b: &BPoly) -> BPoly {
1279    let mut out = BPoly::new();
1280    for (&(i1, j1), c1) in a {
1281        for (&(i2, j2), c2) in b {
1282            let e = out.entry((i1 + i2, j1 + j2)).or_insert_with(BigInt::zero);
1283            *e = e.add(&c1.mul(c2));
1284        }
1285    }
1286    out.retain(|_, c| !c.is_zero());
1287    out
1288}
1289
1290fn bpoly_pow(base: &BPoly, e: u32) -> BPoly {
1291    let mut acc = BPoly::new();
1292    acc.insert((0, 0), one());
1293    for _ in 0..e {
1294        acc = bpoly_mul(&acc, base);
1295    }
1296    acc
1297}
1298
1299fn bpoly_eval(g: &BPoly, x: &BigInt, y: &BigInt) -> BigInt {
1300    g.iter().fold(BigInt::zero(), |acc, (&(i, j), c)| {
1301        acc.add(&c.mul(&x.pow(i)).mul(&y.pow(j)))
1302    })
1303}
1304
1305/// Substitute `x = xv` into a bivariate polynomial, returning the univariate polynomial in `y`
1306/// (coefficients low-to-high).
1307fn bpoly_subst_x(g: &BPoly, xv: &BigInt) -> Vec<BigInt> {
1308    let max_j = g.keys().map(|&(_, j)| j).max().unwrap_or(0) as usize;
1309    let mut uni = vec![BigInt::zero(); max_j + 1];
1310    for (&(i, j), c) in g {
1311        uni[j as usize] = uni[j as usize].add(&c.mul(&xv.pow(i)));
1312    }
1313    uni
1314}
1315
1316/// Build the Boneh–Durfee lattice, LLL-reduce it (fast float-Gram-Schmidt), and return the short
1317/// bivariate polynomials (unscaled) that should share the root `(k, −(p+q))`, plus the `y`-bound.
1318fn bd_reduced_polys(
1319    n: &BigInt,
1320    e: &BigInt,
1321    m: usize,
1322    t: usize,
1323    x_bound: &BigInt,
1324) -> (Vec<BPoly>, BigInt) {
1325    let one = one();
1326    let y_bound = isqrt(n).mul(&BigInt::from_i64(3));
1327
1328    let mut f = BPoly::new();
1329    f.insert((1, 1), one.clone());
1330    f.insert((1, 0), n.add(&one));
1331    f.insert((0, 0), one.clone());
1332
1333    let mut shifts: Vec<BPoly> = Vec::new();
1334    for k in 0..=m {
1335        let fke: BPoly = {
1336            let scale = e.pow((m - k) as u32);
1337            bpoly_pow(&f, k as u32)
1338                .into_iter()
1339                .map(|(key, c)| (key, c.mul(&scale)))
1340                .collect()
1341        };
1342        for i in 0..=(m - k) {
1343            shifts.push(
1344                fke.iter()
1345                    .map(|(&(a, b), c)| ((a + i as u32, b), c.clone()))
1346                    .collect(),
1347            );
1348        }
1349        for j in 1..=t {
1350            shifts.push(
1351                fke.iter()
1352                    .map(|(&(a, b), c)| ((a, b + j as u32), c.clone()))
1353                    .collect(),
1354            );
1355        }
1356    }
1357
1358    let mut monos: std::collections::BTreeSet<(u32, u32)> = std::collections::BTreeSet::new();
1359    for s in &shifts {
1360        monos.extend(s.keys());
1361    }
1362    let monos: Vec<(u32, u32)> = monos.into_iter().collect();
1363    let scale_of: Vec<BigInt> = monos
1364        .iter()
1365        .map(|&(i, j)| x_bound.pow(i).mul(&y_bound.pow(j)))
1366        .collect();
1367    let col: std::collections::HashMap<(u32, u32), usize> =
1368        monos.iter().enumerate().map(|(i, &k)| (k, i)).collect();
1369    let rows: Vec<Vec<BigInt>> = shifts
1370        .iter()
1371        .map(|s| {
1372            let mut row = vec![BigInt::zero(); monos.len()];
1373            for (&key, c) in s {
1374                let ci = col[&key];
1375                row[ci] = c.mul(&scale_of[ci]);
1376            }
1377            row
1378        })
1379        .collect();
1380
1381    let reduced = crate::lattice::lll_reduce_bigint_fp(&rows);
1382    let polys: Vec<BPoly> = reduced
1383        .iter()
1384        .map(|row| {
1385            let mut g = BPoly::new();
1386            for (ci, &key) in monos.iter().enumerate() {
1387                if !row[ci].is_zero() {
1388                    let (q, r) = row[ci].div_rem(&scale_of[ci]).expect("nonzero");
1389                    if r.is_zero() {
1390                        g.insert(key, q);
1391                    }
1392                }
1393            }
1394            g
1395        })
1396        .filter(|g| !g.is_empty())
1397        .collect();
1398    (polys, y_bound)
1399}
1400
1401/// Round-tripping real root candidates of `res` (a univariate polynomial, low-to-high) in `[−bound,
1402/// bound]`, from a floating-point Newton search — proposals, verified exactly by the caller.
1403fn real_root_candidates(res: &[BigInt], bound: &BigInt) -> Vec<BigInt> {
1404    let maxc = res.iter().map(|c| c.abs()).max().filter(|c| !c.is_zero());
1405    let Some(maxc) = maxc else {
1406        return Vec::new();
1407    };
1408    let cf: Vec<f64> = res
1409        .iter()
1410        .map(|c| {
1411            Rational::new(c.clone(), maxc.clone())
1412                .map(|r| r.to_f64())
1413                .unwrap_or(0.0)
1414        })
1415        .collect();
1416    let eval = |x: f64| cf.iter().rev().fold(0.0, |acc, &c| acc * x + c);
1417    let deriv = |x: f64| {
1418        (1..cf.len())
1419            .rev()
1420            .fold(0.0, |acc, k| acc * x + cf[k] * k as f64)
1421    };
1422    let bf = bound.to_f64();
1423    let mut seeds: Vec<f64> = Vec::new();
1424    let mut p = 1.0;
1425    while p <= bf {
1426        seeds.push(p);
1427        seeds.push(-p);
1428        p *= 1.3;
1429    }
1430    let mut out: Vec<BigInt> = Vec::new();
1431    for &s in &seeds {
1432        let mut x = s;
1433        for _ in 0..200 {
1434            let d = deriv(x);
1435            if d.abs() < 1e-18 || !x.is_finite() {
1436                break;
1437            }
1438            let nx = x - eval(x) / d;
1439            if !nx.is_finite() {
1440                break;
1441            }
1442            if (nx - x).abs() < 0.4 {
1443                x = nx;
1444                break;
1445            }
1446            x = nx;
1447        }
1448        if x.is_finite() && x.abs() <= bf * 1.01 {
1449            if let Some(c) = BigInt::parse_decimal(&format!("{:.0}", x.abs())) {
1450                let cand = if x < 0.0 { c.negated() } else { c };
1451                if !out.contains(&cand) {
1452                    out.push(cand);
1453                }
1454            }
1455        }
1456    }
1457    out
1458}
1459
1460/// Boneh–Durfee: recover the factorization from a **small private exponent** `d < N^{0.284}` — beyond
1461/// Wiener's `N^{0.25}` — by bivariate Coppersmith. Since `e·d − 1 = k·φ(N)` and `φ(N) = N + 1 − (p+q)`,
1462/// the polynomial `f(x, y) = x·y + (N+1)·x + 1` has the small root `(x₀, y₀) = (k, −(p+q))` modulo `e`.
1463/// The lattice of `x`- and `y`-shifts of `f`, LLL-reduced (fast float-Gram-Schmidt), yields short bivariate
1464/// polynomials sharing that root; a resultant eliminates `x`, its root gives `s = p+q`, and `z² − s·z + N`
1465/// splits `N`. `m`, `t` size the lattice; `x_bound = N^δ` bounds `k`. Returns `(p, q)` or `None`.
1466pub fn boneh_durfee(
1467    n: &BigInt,
1468    e: &BigInt,
1469    m: usize,
1470    t: usize,
1471    x_bound: &BigInt,
1472) -> Option<(BigInt, BigInt)> {
1473    let (polys, y_bound) = bd_reduced_polys(n, e, m, t, x_bound);
1474
1475    // Read the shared root (k, −s) off the reduced polynomials: k is small (< X), so scan it; substituting
1476    // x = k into a vanishing polynomial gives a low-degree polynomial in y whose root is −s, found
1477    // reliably. `s = p+q` then splits N via z² − s·z + N.
1478    let x_lim = x_bound.to_i64().unwrap_or(0).max(0);
1479    let four_n = BigInt::from_i64(4).mul(n);
1480    let two = two();
1481    for g in polys.iter().take(6) {
1482        for ki in 1..=x_lim {
1483            let k = BigInt::from_i64(ki);
1484            let gy = bpoly_subst_x(g, &k);
1485            if gy.iter().all(|c| c.is_zero()) {
1486                continue;
1487            }
1488            for y0 in integer_roots_of(&gy, &y_bound) {
1489                let s = y0.negated();
1490                if s.is_negative() || s.is_zero() {
1491                    continue;
1492                }
1493                let disc = s.mul(&s).sub(&four_n);
1494                if disc.is_negative() {
1495                    continue;
1496                }
1497                let sq = isqrt(&disc);
1498                if sq.mul(&sq) == disc {
1499                    let p = s.sub(&sq).div_rem(&two).expect("nonzero").0;
1500                    let q = s.add(&sq).div_rem(&two).expect("nonzero").0;
1501                    if verify_factorization(n, &p, &q) {
1502                        return Some((p, q));
1503                    }
1504                }
1505            }
1506        }
1507    }
1508    None
1509}
1510
1511/// The effort budget for [`structural_factor`]: each structural attack runs to its own bound, then
1512/// declines. A soundly-generated modulus exhausts every bound and yields no witness.
1513#[derive(Clone, Copy, Debug)]
1514pub struct StructuralBudget {
1515    pub trial_limit: u64,
1516    pub fermat_iters: u64,
1517    pub pminus1_bound: u64,
1518    pub rho_iters: u64,
1519}
1520
1521impl Default for StructuralBudget {
1522    // A quick structural triage: enough to expose any real structural weakness, but far short of the
1523    // (sub-)exponential effort a sound modulus would demand — so the ceiling is proven cheaply. A
1524    // 200-bit sound modulus needs ~2⁵⁰ rho steps; 5 000 is not remotely close, yet a *structured* key
1525    // falls in a handful of steps regardless.
1526    fn default() -> Self {
1527        Self {
1528            trial_limit: 1_000,
1529            fermat_iters: 3_000,
1530            pminus1_bound: 500,
1531            rho_iters: 5_000,
1532        }
1533    }
1534}
1535
1536/// A certified structural weakness: the factors and the attack that found them.
1537#[derive(Clone, Debug, PartialEq, Eq)]
1538pub struct StructuralWitness {
1539    pub p: BigInt,
1540    pub q: BigInt,
1541    pub method: &'static str,
1542}
1543
1544/// Run the whole structural arsenal against `n` within `budget`, returning the first certified
1545/// factorization found, or `None` — the number-theoretic incompressible residue (a sound modulus has no
1546/// structural shortcut, so only the general sub-exponential algorithms, out of scope here, remain).
1547pub fn structural_factor(n: &BigInt, budget: StructuralBudget) -> Option<StructuralWitness> {
1548    let mk = |(p, q): (BigInt, BigInt), method: &'static str| StructuralWitness { p, q, method };
1549    if let Some(f) = trial_division(n, budget.trial_limit) {
1550        return Some(mk(f, "trial division (small factor)"));
1551    }
1552    if let Some(f) = fermat(n, budget.fermat_iters) {
1553        return Some(mk(f, "Fermat (close primes)"));
1554    }
1555    if let Some(f) = pollard_p_minus_1(n, budget.pminus1_bound) {
1556        return Some(mk(f, "Pollard p−1 (smooth p−1)"));
1557    }
1558    if let Some(f) = pollard_rho(n, budget.rho_iters) {
1559        return Some(mk(f, "Pollard rho"));
1560    }
1561    None
1562}
1563
1564#[cfg(test)]
1565#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/factor/tests.rs"]
1566mod tests;