foxmath 0.20.2__tar.gz → 0.20.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: foxmath
3
- Version: 0.20.2
3
+ Version: 0.20.4
4
4
  Summary: Minimalist CLI & library for number theory and cryptography: Shanks's SQUFOF, Quadratic Sieve & Dixon factoring, Lenstra ECM, Pollard p-1, Lucas-Lehmer Mersenne tests, Fermat factor, RSA & Diffie-Hellman cryptosystems, BSGS discrete log, arithmetic functions (mu, sigma, tau), Jacobi symbol, Tonelli-Shanks, elliptic curves, CRT, and continued fractions.
5
5
  Author-email: Abhrankan Chakrabarti <abhrankan@gmail.com>
6
6
  License: MIT
@@ -33,17 +33,17 @@ Built with curiosity — for students, tinkerers, and crypto/math enthusiasts.
33
33
  - Dixon's random squares integer factorization: sub-exponential integer factorization with quadratic residue factor base and GF(2) linear algebra (dixon)
34
34
  - Lenstra's elliptic curve factorization (ECM): multi-curve two-stage factoring with Weierstrass curves and SplitMix64 PRNG (ecm)
35
35
  - Two-stage Pollard's p-1 integer factorization: Stage 1 prime-power exponentiation with automatic prime backtracking and Stage 2 prime difference table (pm1)
36
- - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and prime exponent search (mersenne)
36
+ - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and live-streaming prime exponent search (--list) (mersenne)
37
37
  - Euclid–Euler perfect number generator and test: 2^(p-1) * (2^p - 1) (perfect)
38
38
  - Fermat's difference of squares factorization: fast factoring when factors are close, with configurable precision, interval, and iteration offset (fermat)
39
39
  - Textbook RSA cryptosystem: key generation, encryption, CRT-accelerated decryption, and multi-method modulus crack (Pollard's ρ & Fermat's attack) (rsa)
40
- - Diffie-Hellman key exchange: key generation, shared secret derivation, and BSGS discrete log attack (dh)
40
+ - Diffie-Hellman key exchange: key generation, RFC 3526 peer key bounds validation (2 <= y <= p - 2), shared secret derivation, and BSGS discrete log attack (dh)
41
41
  - Legendre symbol
42
42
  - Jacobi symbol (jacobi)
43
43
  - Solovay–Strassen probabilistic primality test (solovay)
44
44
  - Modular square root via Tonelli-Shanks (sqrtmod)
45
45
  - Miller-Rabin primality test: deterministic for n < 3.3 × 10²⁴ via 13 bases, strong probable prime above (isprime)
46
- - Prime factorization via Pollard's rho & trial division (factor)
46
+ - Prime factorization via Pollard's rho & trial division with early stderr composite advisory (factor)
47
47
  - Discrete logarithm solver via Baby-step Giant-step (dlog)
48
48
  - Euler's totient φ(n) and Carmichael λ(n) (totient)
49
49
  - Multiplicative order and primitive roots (order)
@@ -87,7 +87,7 @@ Check which version you have installed:
87
87
  foxmath --version
88
88
  ```
89
89
  ```
90
- foxmath 0.16.0
90
+ foxmath 0.20.4
91
91
  ```
92
92
 
93
93
  ## Usage Examples
@@ -211,7 +211,7 @@ M_13 = 2^13 - 1 = 8191
211
211
  ```
212
212
 
213
213
  ```bash
214
- # List all Mersenne prime exponents up to limit
214
+ # List all Mersenne prime exponents up to limit (streams live as primes are found)
215
215
  foxmath mersenne --list --limit 31
216
216
  ```
217
217
  ```
@@ -14,17 +14,17 @@ Built with curiosity — for students, tinkerers, and crypto/math enthusiasts.
14
14
  - Dixon's random squares integer factorization: sub-exponential integer factorization with quadratic residue factor base and GF(2) linear algebra (dixon)
15
15
  - Lenstra's elliptic curve factorization (ECM): multi-curve two-stage factoring with Weierstrass curves and SplitMix64 PRNG (ecm)
16
16
  - Two-stage Pollard's p-1 integer factorization: Stage 1 prime-power exponentiation with automatic prime backtracking and Stage 2 prime difference table (pm1)
17
- - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and prime exponent search (mersenne)
17
+ - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and live-streaming prime exponent search (--list) (mersenne)
18
18
  - Euclid–Euler perfect number generator and test: 2^(p-1) * (2^p - 1) (perfect)
19
19
  - Fermat's difference of squares factorization: fast factoring when factors are close, with configurable precision, interval, and iteration offset (fermat)
20
20
  - Textbook RSA cryptosystem: key generation, encryption, CRT-accelerated decryption, and multi-method modulus crack (Pollard's ρ & Fermat's attack) (rsa)
21
- - Diffie-Hellman key exchange: key generation, shared secret derivation, and BSGS discrete log attack (dh)
21
+ - Diffie-Hellman key exchange: key generation, RFC 3526 peer key bounds validation (2 <= y <= p - 2), shared secret derivation, and BSGS discrete log attack (dh)
22
22
  - Legendre symbol
23
23
  - Jacobi symbol (jacobi)
24
24
  - Solovay–Strassen probabilistic primality test (solovay)
25
25
  - Modular square root via Tonelli-Shanks (sqrtmod)
26
26
  - Miller-Rabin primality test: deterministic for n < 3.3 × 10²⁴ via 13 bases, strong probable prime above (isprime)
27
- - Prime factorization via Pollard's rho & trial division (factor)
27
+ - Prime factorization via Pollard's rho & trial division with early stderr composite advisory (factor)
28
28
  - Discrete logarithm solver via Baby-step Giant-step (dlog)
29
29
  - Euler's totient φ(n) and Carmichael λ(n) (totient)
30
30
  - Multiplicative order and primitive roots (order)
@@ -68,7 +68,7 @@ Check which version you have installed:
68
68
  foxmath --version
69
69
  ```
70
70
  ```
71
- foxmath 0.16.0
71
+ foxmath 0.20.4
72
72
  ```
73
73
 
74
74
  ## Usage Examples
@@ -192,7 +192,7 @@ M_13 = 2^13 - 1 = 8191
192
192
  ```
193
193
 
194
194
  ```bash
195
- # List all Mersenne prime exponents up to limit
195
+ # List all Mersenne prime exponents up to limit (streams live as primes are found)
196
196
  foxmath mersenne --list --limit 31
197
197
  ```
198
198
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "foxmath"
7
- version = "0.20.2"
7
+ version = "0.20.4"
8
8
  description = "Minimalist CLI & library for number theory and cryptography: Shanks's SQUFOF, Quadratic Sieve & Dixon factoring, Lenstra ECM, Pollard p-1, Lucas-Lehmer Mersenne tests, Fermat factor, RSA & Diffie-Hellman cryptosystems, BSGS discrete log, arithmetic functions (mu, sigma, tau), Jacobi symbol, Tonelli-Shanks, elliptic curves, CRT, and continued fractions."
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -113,6 +113,19 @@ def _factor_recursive(n: int, rng: random.Random, factors: list) -> None:
113
113
  _factor_recursive(d, rng, factors)
114
114
  _factor_recursive(n // d, rng, factors)
115
115
 
116
+ _TRIAL_PRIMES_UNDER_100 = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
117
+
118
+ def _strip_small_primes(n: int) -> tuple:
119
+ """Divide out primes under 100 and return (remaining_cofactor, extracted_primes)."""
120
+ factors = []
121
+ for p in _TRIAL_PRIMES_UNDER_100:
122
+ while n % p == 0:
123
+ factors.append(p)
124
+ n //= p
125
+ if n == 1:
126
+ break
127
+ return n, factors
128
+
116
129
  def factorize(n: int) -> list:
117
130
  """Return sorted list of (prime, power) tuples for integer n >= 1.
118
131
 
@@ -125,14 +138,7 @@ def factorize(n: int) -> list:
125
138
  if n == 1:
126
139
  return []
127
140
 
128
- factors = []
129
- # Small prime trial division up to 100
130
- for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97):
131
- while n % p == 0:
132
- factors.append(p)
133
- n //= p
134
- if n == 1:
135
- break
141
+ n, factors = _strip_small_primes(n)
136
142
 
137
143
  if n > 1:
138
144
  if is_prime(n):
@@ -1817,10 +1823,15 @@ def mersenne(p: int) -> dict:
1817
1823
  info["perfect_number"] = (1 << (p - 1)) * mp
1818
1824
  return info
1819
1825
 
1820
- def mersenne_primes(limit_p: int = 127) -> list:
1821
- """Return a list of prime exponents p <= limit_p such that 2^p - 1 is prime."""
1826
+ def mersenne_primes(limit_p: int = 127, on_found=None) -> list:
1827
+ """Return a list of prime exponents p <= limit_p such that 2^p - 1 is prime.
1828
+
1829
+ If on_found is provided, it is called with each discovered exponent as it is verified.
1830
+ """
1822
1831
  if not isinstance(limit_p, int):
1823
1832
  raise TypeError("limit_p must be an integer")
1833
+ if on_found is not None and not callable(on_found):
1834
+ raise TypeError("on_found must be callable")
1824
1835
  if limit_p < 2:
1825
1836
  return []
1826
1837
 
@@ -1828,6 +1839,8 @@ def mersenne_primes(limit_p: int = 127) -> list:
1828
1839
  for p in range(2, limit_p + 1):
1829
1840
  if is_prime(p) and lucas_lehmer(p):
1830
1841
  primes.append(p)
1842
+ if on_found is not None:
1843
+ on_found(p)
1831
1844
  return primes
1832
1845
 
1833
1846
  def perfect_number(p: int) -> int:
@@ -3081,6 +3094,14 @@ def main():
3081
3094
  print(f"{args.n} is {verdict}")
3082
3095
 
3083
3096
  elif cmd == "factor" or args.command == "factor":
3097
+ if not json_output and args.n > 1:
3098
+ rem, _ = _strip_small_primes(args.n)
3099
+ if rem.bit_length() >= 75 and not is_prime(rem):
3100
+ print(
3101
+ f"Factoring {len(str(rem))}-digit ({rem.bit_length()}-bit) composite; this may take a while...",
3102
+ file=sys.stderr,
3103
+ flush=True,
3104
+ )
3084
3105
  factors = factorize(args.n)
3085
3106
  is_p = is_prime(args.n)
3086
3107
  expr = format_factorization(factors)
@@ -3442,7 +3463,21 @@ def main():
3442
3463
 
3443
3464
  elif cmd == "mersenne" or args.command == "mersenne":
3444
3465
  if args.list:
3445
- m_primes = mersenne_primes(args.limit)
3466
+ if not json_output:
3467
+ print(f"Mersenne prime exponents p <= {args.limit}:", flush=True)
3468
+ print(" ", end="", flush=True)
3469
+ first = True
3470
+
3471
+ def _stream_exponent(p: int) -> None:
3472
+ nonlocal first
3473
+ prefix = "" if first else ", "
3474
+ first = False
3475
+ print(f"{prefix}{p}", end="", flush=True)
3476
+
3477
+ m_primes = mersenne_primes(args.limit, on_found=_stream_exponent)
3478
+ print(f" ({len(m_primes)} primes)")
3479
+ else:
3480
+ m_primes = mersenne_primes(args.limit)
3446
3481
  result.update({
3447
3482
  "command": "mersenne",
3448
3483
  "action": "list",
@@ -3450,9 +3485,6 @@ def main():
3450
3485
  "exponents": m_primes,
3451
3486
  "count": len(m_primes),
3452
3487
  })
3453
- if not json_output:
3454
- print(f"Mersenne prime exponents p <= {args.limit}:")
3455
- print(f" {', '.join(str(p) for p in m_primes)} ({len(m_primes)} primes)")
3456
3488
  else:
3457
3489
  if args.p is None:
3458
3490
  raise ValueError("Specify exponent p or use --list")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: foxmath
3
- Version: 0.20.2
3
+ Version: 0.20.4
4
4
  Summary: Minimalist CLI & library for number theory and cryptography: Shanks's SQUFOF, Quadratic Sieve & Dixon factoring, Lenstra ECM, Pollard p-1, Lucas-Lehmer Mersenne tests, Fermat factor, RSA & Diffie-Hellman cryptosystems, BSGS discrete log, arithmetic functions (mu, sigma, tau), Jacobi symbol, Tonelli-Shanks, elliptic curves, CRT, and continued fractions.
5
5
  Author-email: Abhrankan Chakrabarti <abhrankan@gmail.com>
6
6
  License: MIT
@@ -33,17 +33,17 @@ Built with curiosity — for students, tinkerers, and crypto/math enthusiasts.
33
33
  - Dixon's random squares integer factorization: sub-exponential integer factorization with quadratic residue factor base and GF(2) linear algebra (dixon)
34
34
  - Lenstra's elliptic curve factorization (ECM): multi-curve two-stage factoring with Weierstrass curves and SplitMix64 PRNG (ecm)
35
35
  - Two-stage Pollard's p-1 integer factorization: Stage 1 prime-power exponentiation with automatic prime backtracking and Stage 2 prime difference table (pm1)
36
- - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and prime exponent search (mersenne)
36
+ - Lucas–Lehmer deterministic primality test for Mersenne numbers M_p = 2^p - 1 and live-streaming prime exponent search (--list) (mersenne)
37
37
  - Euclid–Euler perfect number generator and test: 2^(p-1) * (2^p - 1) (perfect)
38
38
  - Fermat's difference of squares factorization: fast factoring when factors are close, with configurable precision, interval, and iteration offset (fermat)
39
39
  - Textbook RSA cryptosystem: key generation, encryption, CRT-accelerated decryption, and multi-method modulus crack (Pollard's ρ & Fermat's attack) (rsa)
40
- - Diffie-Hellman key exchange: key generation, shared secret derivation, and BSGS discrete log attack (dh)
40
+ - Diffie-Hellman key exchange: key generation, RFC 3526 peer key bounds validation (2 <= y <= p - 2), shared secret derivation, and BSGS discrete log attack (dh)
41
41
  - Legendre symbol
42
42
  - Jacobi symbol (jacobi)
43
43
  - Solovay–Strassen probabilistic primality test (solovay)
44
44
  - Modular square root via Tonelli-Shanks (sqrtmod)
45
45
  - Miller-Rabin primality test: deterministic for n < 3.3 × 10²⁴ via 13 bases, strong probable prime above (isprime)
46
- - Prime factorization via Pollard's rho & trial division (factor)
46
+ - Prime factorization via Pollard's rho & trial division with early stderr composite advisory (factor)
47
47
  - Discrete logarithm solver via Baby-step Giant-step (dlog)
48
48
  - Euler's totient φ(n) and Carmichael λ(n) (totient)
49
49
  - Multiplicative order and primitive roots (order)
@@ -87,7 +87,7 @@ Check which version you have installed:
87
87
  foxmath --version
88
88
  ```
89
89
  ```
90
- foxmath 0.16.0
90
+ foxmath 0.20.4
91
91
  ```
92
92
 
93
93
  ## Usage Examples
@@ -211,7 +211,7 @@ M_13 = 2^13 - 1 = 8191
211
211
  ```
212
212
 
213
213
  ```bash
214
- # List all Mersenne prime exponents up to limit
214
+ # List all Mersenne prime exponents up to limit (streams live as primes are found)
215
215
  foxmath mersenne --list --limit 31
216
216
  ```
217
217
  ```
@@ -1169,6 +1169,37 @@ class TestFermatStdin(unittest.TestCase):
1169
1169
  self.assertEqual(proc.returncode, 0, err)
1170
1170
  self.assertIn("Factors of 15", out)
1171
1171
 
1172
+
1173
+ class TestDiffieHellmanPeerKeyCLI(unittest.TestCase):
1174
+ def test_dh_derive_rejects_degenerate_peer_keys(self):
1175
+ for peer in ("1", "22"): # 1 and p - 1 for p = 23
1176
+ code, out, err = run("dh", "derive", "4", peer, "23")
1177
+ self.assertEqual(code, 1, peer)
1178
+ self.assertIn("2 <= key <= p - 2", err)
1179
+
1180
+
1181
+ class TestLongRunFeedbackCLI(unittest.TestCase):
1182
+ def test_factor_warns_on_stderr_for_large_composite(self):
1183
+ # 1000000007 * 10000000000000061 (84-bit composite, fast to factor via Pollard's rho)
1184
+ code, out, err = run("factor", "10000000070000061000000427")
1185
+ self.assertEqual(code, 0, err)
1186
+ self.assertIn("1000000007 * 10000000000000061", out)
1187
+ self.assertIn("this may take a while", err)
1188
+
1189
+ def test_factor_silent_on_stderr_for_json_or_smooth(self):
1190
+ code, out, err = run("factor", "10000000070000061000000427", "--json")
1191
+ self.assertEqual(code, 0, err)
1192
+ self.assertEqual(err.strip(), "")
1193
+ code2, out2, err2 = run("factor", str(2 ** 100))
1194
+ self.assertEqual(code2, 0, err2)
1195
+ self.assertEqual(err2.strip(), "")
1196
+
1197
+ def test_mersenne_list_empty_format_preserved(self):
1198
+ code, out, err = run("mersenne", "--list", "--limit", "1")
1199
+ self.assertEqual(code, 0, err)
1200
+ self.assertIn("Mersenne prime exponents p <= 1:", out)
1201
+ self.assertIn("(0 primes)", out)
1202
+
1172
1203
  if __name__ == "__main__":
1173
1204
  unittest.main()
1174
1205
 
@@ -1275,5 +1275,34 @@ class TestReviewRegressions(unittest.TestCase):
1275
1275
  discrete_log(3, 5, 2 ** 61 - 1)
1276
1276
 
1277
1277
 
1278
+
1279
+ class TestDiffieHellmanPeerKeyBounds(unittest.TestCase):
1280
+ """dh_derive must refuse peer keys that force the shared secret (1, p-1) or are out of range."""
1281
+ P = 1000003 # prime
1282
+
1283
+ def setUp(self):
1284
+ from foxmath.foxmath import dh_keygen
1285
+ self.priv = dh_keygen(self.P, 2, seed=1)["private_key"]
1286
+
1287
+ def test_rejects_degenerate_and_out_of_range_peer_keys(self):
1288
+ from foxmath.foxmath import dh_derive
1289
+ for bad in (-3, 0, 1, self.P - 1, self.P, self.P + 7):
1290
+ with self.subTest(peer=bad):
1291
+ with self.assertRaisesRegex(ValueError, "2 <= key <= p - 2"):
1292
+ dh_derive(self.priv, bad, self.P)
1293
+
1294
+ def test_accepts_the_boundary_values_2_and_p_minus_2(self):
1295
+ from foxmath.foxmath import dh_derive
1296
+ for ok in (2, self.P - 2):
1297
+ with self.subTest(peer=ok):
1298
+ self.assertIsInstance(dh_derive(self.priv, ok, self.P), int)
1299
+
1300
+ def test_both_sides_derive_the_same_secret(self):
1301
+ from foxmath.foxmath import dh_keygen, dh_derive
1302
+ a = dh_keygen(self.P, 2, seed=1)
1303
+ b = dh_keygen(self.P, 2, seed=2)
1304
+ self.assertEqual(dh_derive(a["private_key"], b["public_key"], self.P),
1305
+ dh_derive(b["private_key"], a["public_key"], self.P))
1306
+
1278
1307
  if __name__ == "__main__":
1279
1308
  unittest.main()
@@ -100,6 +100,16 @@ class TestMersennePrimesList(unittest.TestCase):
100
100
  with self.assertRaises(TypeError):
101
101
  mersenne_primes("31")
102
102
 
103
+ def test_list_on_found_streams_each_exponent(self):
104
+ seen = []
105
+ result = mersenne_primes(31, on_found=seen.append)
106
+ self.assertEqual(seen, [2, 3, 5, 7, 13, 17, 19, 31])
107
+ self.assertEqual(seen, result)
108
+
109
+ def test_list_invalid_on_found_raises(self):
110
+ with self.assertRaises(TypeError):
111
+ mersenne_primes(31, on_found=123)
112
+
103
113
 
104
114
  class TestPerfectNumbers(unittest.TestCase):
105
115
  def test_is_perfect(self):
File without changes
File without changes