Skip to content

Commit

Permalink
Merge pull request #220 from tomato42/fast-native-inverse
Browse files Browse the repository at this point in the history
use native inverse modulo when available
  • Loading branch information
tomato42 committed Dec 3, 2020
2 parents 90bb8ae + 0d5dffa commit 58ea273
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -42,6 +42,7 @@ If `gmpy2` or `gmpy` is installed, they will be used for faster arithmetic.
Either of them can be installed after this library is installed,
`python-ecdsa` will detect their presence on start-up and use them
automatically.
You should prefer `gmpy2` on Python3 for optimal performance.

To run the OpenSSL compatibility tests, the 'openssl' tool must be in your
`PATH`. This release has been tested successfully against OpenSSL 0.9.8o,
Expand Down
24 changes: 17 additions & 7 deletions src/ecdsa/numbertheory.py
Expand Up @@ -11,6 +11,7 @@

from __future__ import division

import sys
from six import integer_types, PY2
from six.moves import reduce

Expand Down Expand Up @@ -219,7 +220,7 @@ def square_root_mod_prime(a, p):
raise RuntimeError("No b found.")


if GMPY2:
if GMPY2: # pragma: no branch

def inverse_mod(a, m):
"""Inverse of a mod m."""
Expand All @@ -228,14 +229,14 @@ def inverse_mod(a, m):
return powmod(a, -1, m)


elif GMPY:
elif GMPY: # pragma: no branch

def inverse_mod(a, m):
"""Inverse of a mod m."""
# while libgmp likely does support inverses modulo, it is accessible
# only using the native `pow()` function, and `pow()` sanity checks
# the parameters before passing them on to underlying implementation
# on Python2
# while libgmp does support inverses modulo, it is accessible
# only using the native `pow()` function, and `pow()` in gmpy sanity
# checks the parameters before passing them on to underlying
# implementation
if a == 0:
return 0
a = mpz(a)
Expand All @@ -250,7 +251,16 @@ def inverse_mod(a, m):
return lm % m


else:
elif sys.version_info >= (3, 8): # pragma: no branch

def inverse_mod(a, m):
"""Inverse of a mod m."""
if a == 0:
return 0
return pow(a, -1, m)


else: # pragma: no branch

def inverse_mod(a, m):
"""Inverse of a mod m."""
Expand Down

0 comments on commit 58ea273

Please sign in to comment.