Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

836 рядки
17 KiB

  1. #! /usr/bin/env python
  2. #
  3. # Provide some simple capabilities from number theory.
  4. #
  5. # Version of 2008.11.14.
  6. #
  7. # Written in 2005 and 2006 by Peter Pearson and placed in the public domain.
  8. # Revision history:
  9. # 2008.11.14: Use pow(base, exponent, modulus) for modular_exp.
  10. # Make gcd and lcm accept arbitrarily many arguments.
  11. from __future__ import division
  12. import sys
  13. from six import integer_types, PY2
  14. from six.moves import reduce
  15. try:
  16. xrange
  17. except NameError:
  18. xrange = range
  19. try:
  20. from gmpy2 import powmod, mpz
  21. GMPY2 = True
  22. GMPY = False
  23. except ImportError: # pragma: no branch
  24. GMPY2 = False
  25. try:
  26. from gmpy import mpz
  27. GMPY = True
  28. except ImportError:
  29. GMPY = False
  30. if GMPY2 or GMPY: # pragma: no branch
  31. integer_types = tuple(integer_types + (type(mpz(1)),))
  32. import math
  33. import warnings
  34. import random
  35. from .util import bit_length
  36. class Error(Exception):
  37. """Base class for exceptions in this module."""
  38. pass
  39. class JacobiError(Error):
  40. pass
  41. class SquareRootError(Error):
  42. pass
  43. class NegativeExponentError(Error):
  44. pass
  45. def modular_exp(base, exponent, modulus): # pragma: no cover
  46. """Raise base to exponent, reducing by modulus"""
  47. # deprecated in 0.14
  48. warnings.warn(
  49. "Function is unused in library code. If you use this code, "
  50. "change to pow() builtin.",
  51. DeprecationWarning,
  52. )
  53. if exponent < 0:
  54. raise NegativeExponentError(
  55. "Negative exponents (%d) not allowed" % exponent
  56. )
  57. return pow(base, exponent, modulus)
  58. def polynomial_reduce_mod(poly, polymod, p):
  59. """Reduce poly by polymod, integer arithmetic modulo p.
  60. Polynomials are represented as lists of coefficients
  61. of increasing powers of x."""
  62. # This module has been tested only by extensive use
  63. # in calculating modular square roots.
  64. # Just to make this easy, require a monic polynomial:
  65. assert polymod[-1] == 1
  66. assert len(polymod) > 1
  67. while len(poly) >= len(polymod):
  68. if poly[-1] != 0:
  69. for i in xrange(2, len(polymod) + 1):
  70. poly[-i] = (poly[-i] - poly[-1] * polymod[-i]) % p
  71. poly = poly[0:-1]
  72. return poly
  73. def polynomial_multiply_mod(m1, m2, polymod, p):
  74. """Polynomial multiplication modulo a polynomial over ints mod p.
  75. Polynomials are represented as lists of coefficients
  76. of increasing powers of x."""
  77. # This is just a seat-of-the-pants implementation.
  78. # This module has been tested only by extensive use
  79. # in calculating modular square roots.
  80. # Initialize the product to zero:
  81. prod = (len(m1) + len(m2) - 1) * [0]
  82. # Add together all the cross-terms:
  83. for i in xrange(len(m1)):
  84. for j in xrange(len(m2)):
  85. prod[i + j] = (prod[i + j] + m1[i] * m2[j]) % p
  86. return polynomial_reduce_mod(prod, polymod, p)
  87. def polynomial_exp_mod(base, exponent, polymod, p):
  88. """Polynomial exponentiation modulo a polynomial over ints mod p.
  89. Polynomials are represented as lists of coefficients
  90. of increasing powers of x."""
  91. # Based on the Handbook of Applied Cryptography, algorithm 2.227.
  92. # This module has been tested only by extensive use
  93. # in calculating modular square roots.
  94. assert exponent < p
  95. if exponent == 0:
  96. return [1]
  97. G = base
  98. k = exponent
  99. if k % 2 == 1:
  100. s = G
  101. else:
  102. s = [1]
  103. while k > 1:
  104. k = k // 2
  105. G = polynomial_multiply_mod(G, G, polymod, p)
  106. if k % 2 == 1:
  107. s = polynomial_multiply_mod(G, s, polymod, p)
  108. return s
  109. def jacobi(a, n):
  110. """Jacobi symbol"""
  111. # Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
  112. # This function has been tested by comparison with a small
  113. # table printed in HAC, and by extensive use in calculating
  114. # modular square roots.
  115. if not n >= 3:
  116. raise JacobiError("n must be larger than 2")
  117. if not n % 2 == 1:
  118. raise JacobiError("n must be odd")
  119. a = a % n
  120. if a == 0:
  121. return 0
  122. if a == 1:
  123. return 1
  124. a1, e = a, 0
  125. while a1 % 2 == 0:
  126. a1, e = a1 // 2, e + 1
  127. if e % 2 == 0 or n % 8 == 1 or n % 8 == 7:
  128. s = 1
  129. else:
  130. s = -1
  131. if a1 == 1:
  132. return s
  133. if n % 4 == 3 and a1 % 4 == 3:
  134. s = -s
  135. return s * jacobi(n % a1, a1)
  136. def square_root_mod_prime(a, p):
  137. """Modular square root of a, mod p, p prime."""
  138. # Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.
  139. # This module has been tested for all values in [0,p-1] for
  140. # every prime p from 3 to 1229.
  141. assert 0 <= a < p
  142. assert 1 < p
  143. if a == 0:
  144. return 0
  145. if p == 2:
  146. return a
  147. jac = jacobi(a, p)
  148. if jac == -1:
  149. raise SquareRootError("%d has no square root modulo %d" % (a, p))
  150. if p % 4 == 3:
  151. return pow(a, (p + 1) // 4, p)
  152. if p % 8 == 5:
  153. d = pow(a, (p - 1) // 4, p)
  154. if d == 1:
  155. return pow(a, (p + 3) // 8, p)
  156. assert d == p - 1
  157. return (2 * a * pow(4 * a, (p - 5) // 8, p)) % p
  158. if PY2:
  159. # xrange on python2 can take integers representable as C long only
  160. range_top = min(0x7FFFFFFF, p)
  161. else:
  162. range_top = p
  163. for b in xrange(2, range_top): # pragma: no branch
  164. if jacobi(b * b - 4 * a, p) == -1:
  165. f = (a, -b, 1)
  166. ff = polynomial_exp_mod((0, 1), (p + 1) // 2, f, p)
  167. if ff[1]:
  168. raise SquareRootError("p is not prime")
  169. return ff[0]
  170. # just an assertion
  171. raise RuntimeError("No b found.") # pragma: no cover
  172. # because all the inverse_mod code is arch/environment specific, and coveralls
  173. # expects it to execute equal number of times, we need to waive it by
  174. # adding the "no branch" pragma to all branches
  175. if GMPY2: # pragma: no branch
  176. def inverse_mod(a, m):
  177. """Inverse of a mod m."""
  178. if a == 0: # pragma: no branch
  179. return 0
  180. return powmod(a, -1, m)
  181. elif GMPY: # pragma: no branch
  182. def inverse_mod(a, m):
  183. """Inverse of a mod m."""
  184. # while libgmp does support inverses modulo, it is accessible
  185. # only using the native `pow()` function, and `pow()` in gmpy sanity
  186. # checks the parameters before passing them on to underlying
  187. # implementation
  188. if a == 0: # pragma: no branch
  189. return 0
  190. a = mpz(a)
  191. m = mpz(m)
  192. lm, hm = mpz(1), mpz(0)
  193. low, high = a % m, m
  194. while low > 1: # pragma: no branch
  195. r = high // low
  196. lm, low, hm, high = hm - lm * r, high - low * r, lm, low
  197. return lm % m
  198. elif sys.version_info >= (3, 8): # pragma: no branch
  199. def inverse_mod(a, m):
  200. """Inverse of a mod m."""
  201. if a == 0: # pragma: no branch
  202. return 0
  203. return pow(a, -1, m)
  204. else: # pragma: no branch
  205. def inverse_mod(a, m):
  206. """Inverse of a mod m."""
  207. if a == 0: # pragma: no branch
  208. return 0
  209. lm, hm = 1, 0
  210. low, high = a % m, m
  211. while low > 1: # pragma: no branch
  212. r = high // low
  213. lm, low, hm, high = hm - lm * r, high - low * r, lm, low
  214. return lm % m
  215. try:
  216. gcd2 = math.gcd
  217. except AttributeError:
  218. def gcd2(a, b):
  219. """Greatest common divisor using Euclid's algorithm."""
  220. while a:
  221. a, b = b % a, a
  222. return b
  223. def gcd(*a):
  224. """Greatest common divisor.
  225. Usage: gcd([ 2, 4, 6 ])
  226. or: gcd(2, 4, 6)
  227. """
  228. if len(a) > 1:
  229. return reduce(gcd2, a)
  230. if hasattr(a[0], "__iter__"):
  231. return reduce(gcd2, a[0])
  232. return a[0]
  233. def lcm2(a, b):
  234. """Least common multiple of two integers."""
  235. return (a * b) // gcd(a, b)
  236. def lcm(*a):
  237. """Least common multiple.
  238. Usage: lcm([ 3, 4, 5 ])
  239. or: lcm(3, 4, 5)
  240. """
  241. if len(a) > 1:
  242. return reduce(lcm2, a)
  243. if hasattr(a[0], "__iter__"):
  244. return reduce(lcm2, a[0])
  245. return a[0]
  246. def factorization(n):
  247. """Decompose n into a list of (prime,exponent) pairs."""
  248. assert isinstance(n, integer_types)
  249. if n < 2:
  250. return []
  251. result = []
  252. # Test the small primes:
  253. for d in smallprimes:
  254. if d > n:
  255. break
  256. q, r = divmod(n, d)
  257. if r == 0:
  258. count = 1
  259. while d <= n: # pragma: no branch
  260. n = q
  261. q, r = divmod(n, d)
  262. if r != 0:
  263. break
  264. count = count + 1
  265. result.append((d, count))
  266. # If n is still greater than the last of our small primes,
  267. # it may require further work:
  268. if n > smallprimes[-1]:
  269. if is_prime(n): # If what's left is prime, it's easy:
  270. result.append((n, 1))
  271. else: # Ugh. Search stupidly for a divisor:
  272. d = smallprimes[-1]
  273. while 1:
  274. d = d + 2 # Try the next divisor.
  275. q, r = divmod(n, d)
  276. if q < d: # n < d*d means we're done, n = 1 or prime.
  277. break
  278. if r == 0: # d divides n. How many times?
  279. count = 1
  280. n = q
  281. # As long as d might still divide n,
  282. while d <= n: # pragma: no branch
  283. q, r = divmod(n, d) # see if it does.
  284. if r != 0:
  285. break
  286. n = q # It does. Reduce n, increase count.
  287. count = count + 1
  288. result.append((d, count))
  289. if n > 1:
  290. result.append((n, 1))
  291. return result
  292. def phi(n): # pragma: no cover
  293. """Return the Euler totient function of n."""
  294. # deprecated in 0.14
  295. warnings.warn(
  296. "Function is unused by library code. If you use this code, "
  297. "please open an issue in "
  298. "https://github.com/tlsfuzzer/python-ecdsa",
  299. DeprecationWarning,
  300. )
  301. assert isinstance(n, integer_types)
  302. if n < 3:
  303. return 1
  304. result = 1
  305. ff = factorization(n)
  306. for f in ff:
  307. e = f[1]
  308. if e > 1:
  309. result = result * f[0] ** (e - 1) * (f[0] - 1)
  310. else:
  311. result = result * (f[0] - 1)
  312. return result
  313. def carmichael(n): # pragma: no cover
  314. """Return Carmichael function of n.
  315. Carmichael(n) is the smallest integer x such that
  316. m**x = 1 mod n for all m relatively prime to n.
  317. """
  318. # deprecated in 0.14
  319. warnings.warn(
  320. "Function is unused by library code. If you use this code, "
  321. "please open an issue in "
  322. "https://github.com/tlsfuzzer/python-ecdsa",
  323. DeprecationWarning,
  324. )
  325. return carmichael_of_factorized(factorization(n))
  326. def carmichael_of_factorized(f_list): # pragma: no cover
  327. """Return the Carmichael function of a number that is
  328. represented as a list of (prime,exponent) pairs.
  329. """
  330. # deprecated in 0.14
  331. warnings.warn(
  332. "Function is unused by library code. If you use this code, "
  333. "please open an issue in "
  334. "https://github.com/tlsfuzzer/python-ecdsa",
  335. DeprecationWarning,
  336. )
  337. if len(f_list) < 1:
  338. return 1
  339. result = carmichael_of_ppower(f_list[0])
  340. for i in xrange(1, len(f_list)):
  341. result = lcm(result, carmichael_of_ppower(f_list[i]))
  342. return result
  343. def carmichael_of_ppower(pp): # pragma: no cover
  344. """Carmichael function of the given power of the given prime."""
  345. # deprecated in 0.14
  346. warnings.warn(
  347. "Function is unused by library code. If you use this code, "
  348. "please open an issue in "
  349. "https://github.com/tlsfuzzer/python-ecdsa",
  350. DeprecationWarning,
  351. )
  352. p, a = pp
  353. if p == 2 and a > 2:
  354. return 2 ** (a - 2)
  355. else:
  356. return (p - 1) * p ** (a - 1)
  357. def order_mod(x, m): # pragma: no cover
  358. """Return the order of x in the multiplicative group mod m."""
  359. # deprecated in 0.14
  360. warnings.warn(
  361. "Function is unused by library code. If you use this code, "
  362. "please open an issue in "
  363. "https://github.com/tlsfuzzer/python-ecdsa",
  364. DeprecationWarning,
  365. )
  366. # Warning: this implementation is not very clever, and will
  367. # take a long time if m is very large.
  368. if m <= 1:
  369. return 0
  370. assert gcd(x, m) == 1
  371. z = x
  372. result = 1
  373. while z != 1:
  374. z = (z * x) % m
  375. result = result + 1
  376. return result
  377. def largest_factor_relatively_prime(a, b): # pragma: no cover
  378. """Return the largest factor of a relatively prime to b."""
  379. # deprecated in 0.14
  380. warnings.warn(
  381. "Function is unused by library code. If you use this code, "
  382. "please open an issue in "
  383. "https://github.com/tlsfuzzer/python-ecdsa",
  384. DeprecationWarning,
  385. )
  386. while 1:
  387. d = gcd(a, b)
  388. if d <= 1:
  389. break
  390. b = d
  391. while 1:
  392. q, r = divmod(a, d)
  393. if r > 0:
  394. break
  395. a = q
  396. return a
  397. def kinda_order_mod(x, m): # pragma: no cover
  398. """Return the order of x in the multiplicative group mod m',
  399. where m' is the largest factor of m relatively prime to x.
  400. """
  401. # deprecated in 0.14
  402. warnings.warn(
  403. "Function is unused by library code. If you use this code, "
  404. "please open an issue in "
  405. "https://github.com/tlsfuzzer/python-ecdsa",
  406. DeprecationWarning,
  407. )
  408. return order_mod(x, largest_factor_relatively_prime(m, x))
  409. def is_prime(n):
  410. """Return True if x is prime, False otherwise.
  411. We use the Miller-Rabin test, as given in Menezes et al. p. 138.
  412. This test is not exact: there are composite values n for which
  413. it returns True.
  414. In testing the odd numbers from 10000001 to 19999999,
  415. about 66 composites got past the first test,
  416. 5 got past the second test, and none got past the third.
  417. Since factors of 2, 3, 5, 7, and 11 were detected during
  418. preliminary screening, the number of numbers tested by
  419. Miller-Rabin was (19999999 - 10000001)*(2/3)*(4/5)*(6/7)
  420. = 4.57 million.
  421. """
  422. # (This is used to study the risk of false positives:)
  423. global miller_rabin_test_count
  424. miller_rabin_test_count = 0
  425. if n <= smallprimes[-1]:
  426. if n in smallprimes:
  427. return True
  428. else:
  429. return False
  430. # 2310 = 2 * 3 * 5 * 7 * 11
  431. if gcd(n, 2310) != 1:
  432. return False
  433. # Choose a number of iterations sufficient to reduce the
  434. # probability of accepting a composite below 2**-80
  435. # (from Menezes et al. Table 4.4):
  436. t = 40
  437. n_bits = 1 + bit_length(n)
  438. assert 11 <= n_bits <= 16384
  439. for k, tt in (
  440. (100, 27),
  441. (150, 18),
  442. (200, 15),
  443. (250, 12),
  444. (300, 9),
  445. (350, 8),
  446. (400, 7),
  447. (450, 6),
  448. (550, 5),
  449. (650, 4),
  450. (850, 3),
  451. (1300, 2),
  452. ):
  453. if n_bits < k:
  454. break
  455. t = tt
  456. # Run the test t times:
  457. s = 0
  458. r = n - 1
  459. while (r % 2) == 0:
  460. s = s + 1
  461. r = r // 2
  462. for i in xrange(t):
  463. a = random.choice(smallprimes)
  464. y = pow(a, r, n)
  465. if y != 1 and y != n - 1:
  466. j = 1
  467. while j <= s - 1 and y != n - 1:
  468. y = pow(y, 2, n)
  469. if y == 1:
  470. miller_rabin_test_count = i + 1
  471. return False
  472. j = j + 1
  473. if y != n - 1:
  474. miller_rabin_test_count = i + 1
  475. return False
  476. return True
  477. def next_prime(starting_value):
  478. """Return the smallest prime larger than the starting value."""
  479. if starting_value < 2:
  480. return 2
  481. result = (starting_value + 1) | 1
  482. while not is_prime(result):
  483. result = result + 2
  484. return result
  485. smallprimes = [
  486. 2,
  487. 3,
  488. 5,
  489. 7,
  490. 11,
  491. 13,
  492. 17,
  493. 19,
  494. 23,
  495. 29,
  496. 31,
  497. 37,
  498. 41,
  499. 43,
  500. 47,
  501. 53,
  502. 59,
  503. 61,
  504. 67,
  505. 71,
  506. 73,
  507. 79,
  508. 83,
  509. 89,
  510. 97,
  511. 101,
  512. 103,
  513. 107,
  514. 109,
  515. 113,
  516. 127,
  517. 131,
  518. 137,
  519. 139,
  520. 149,
  521. 151,
  522. 157,
  523. 163,
  524. 167,
  525. 173,
  526. 179,
  527. 181,
  528. 191,
  529. 193,
  530. 197,
  531. 199,
  532. 211,
  533. 223,
  534. 227,
  535. 229,
  536. 233,
  537. 239,
  538. 241,
  539. 251,
  540. 257,
  541. 263,
  542. 269,
  543. 271,
  544. 277,
  545. 281,
  546. 283,
  547. 293,
  548. 307,
  549. 311,
  550. 313,
  551. 317,
  552. 331,
  553. 337,
  554. 347,
  555. 349,
  556. 353,
  557. 359,
  558. 367,
  559. 373,
  560. 379,
  561. 383,
  562. 389,
  563. 397,
  564. 401,
  565. 409,
  566. 419,
  567. 421,
  568. 431,
  569. 433,
  570. 439,
  571. 443,
  572. 449,
  573. 457,
  574. 461,
  575. 463,
  576. 467,
  577. 479,
  578. 487,
  579. 491,
  580. 499,
  581. 503,
  582. 509,
  583. 521,
  584. 523,
  585. 541,
  586. 547,
  587. 557,
  588. 563,
  589. 569,
  590. 571,
  591. 577,
  592. 587,
  593. 593,
  594. 599,
  595. 601,
  596. 607,
  597. 613,
  598. 617,
  599. 619,
  600. 631,
  601. 641,
  602. 643,
  603. 647,
  604. 653,
  605. 659,
  606. 661,
  607. 673,
  608. 677,
  609. 683,
  610. 691,
  611. 701,
  612. 709,
  613. 719,
  614. 727,
  615. 733,
  616. 739,
  617. 743,
  618. 751,
  619. 757,
  620. 761,
  621. 769,
  622. 773,
  623. 787,
  624. 797,
  625. 809,
  626. 811,
  627. 821,
  628. 823,
  629. 827,
  630. 829,
  631. 839,
  632. 853,
  633. 857,
  634. 859,
  635. 863,
  636. 877,
  637. 881,
  638. 883,
  639. 887,
  640. 907,
  641. 911,
  642. 919,
  643. 929,
  644. 937,
  645. 941,
  646. 947,
  647. 953,
  648. 967,
  649. 971,
  650. 977,
  651. 983,
  652. 991,
  653. 997,
  654. 1009,
  655. 1013,
  656. 1019,
  657. 1021,
  658. 1031,
  659. 1033,
  660. 1039,
  661. 1049,
  662. 1051,
  663. 1061,
  664. 1063,
  665. 1069,
  666. 1087,
  667. 1091,
  668. 1093,
  669. 1097,
  670. 1103,
  671. 1109,
  672. 1117,
  673. 1123,
  674. 1129,
  675. 1151,
  676. 1153,
  677. 1163,
  678. 1171,
  679. 1181,
  680. 1187,
  681. 1193,
  682. 1201,
  683. 1213,
  684. 1217,
  685. 1223,
  686. 1229,
  687. ]
  688. miller_rabin_test_count = 0