"""
Low level implementation of Elliptic-Curve Digital Signatures.
.. note ::
You're most likely looking for the :py:class:`~ecdsa.keys` module.
This is a low-level implementation of the ECDSA that operates on
integers, not byte strings.
NOTE: This a low level implementation of ECDSA, for normal applications
you should be looking at the keys.py module.
Classes and methods for elliptic-curve signatures:
private keys, public keys, signatures, and definitions of prime-modulus curves.
Example:
.. code-block:: python
# (In real-life applications, you would probably want to # protect against defects in SystemRandom.) from random import SystemRandom
randrange = SystemRandom().randrange
# Generate a public/private key pair using the NIST Curve P-192:
g = generator_192
n = g.order()
secret = randrange( 1, n )
pubkey = Public_key( g, g * secret )
privkey = Private_key( pubkey, secret )
# Signing a hash value:
hash = randrange( 1, n )
signature = privkey.sign( hash, randrange( 1, n ) )
# Verification fails if the hash value is modified:
if pubkey.verifies( hash-1, signature ):
print("**** Demo verification failed to reject tampered hash.") else:
print("Demo verification correctly rejected tampered hash.")
Revision history: 2005.12.31 - Initial version.
2008.11.25 - Substantial revisions introducing new classes.
2009.05.16 - Warn against using random.randrange in real applications.
2009.05.17 - Use random.SystemRandom by default.
Originally written in2005 by Peter Pearson and placed in the public domain,
modified as part of the python-ecdsa package. """
import warnings from six import int2byte from . import ellipticcurve from . import numbertheory from .util import bit_length from ._compat import remove_whitespace
class RSZeroError(RuntimeError): pass
class InvalidPointError(RuntimeError): pass
class Signature(object): """
ECDSA signature.
:ivar int r: the ``r`` element of the ECDSA signature
:ivar int s: the ``s`` element of the ECDSA signature """
def __init__(self, r, s):
self.r = r
self.s = s
def recover_public_keys(self, hash, generator): """
Returns two public keys for which the signature is valid
:param int hash: signed hash
:param AbstractPoint generator: is the generator used in creation
of the signature
:rtype: tuple(Public_key, Public_key)
:return: a pair of public keys that can validate the signature """
curve = generator.curve()
n = generator.order()
r = self.r
s = self.s
e = hash
x = r
# Compute the curve point with x as x-coordinate
alpha = (
pow(x, 3, curve.p()) + (curve.a() * x) + curve.b()
) % curve.p()
beta = numbertheory.square_root_mod_prime(alpha, curve.p())
y = beta if beta % 2 == 0else curve.p() - beta
# Compute the public key
R1 = ellipticcurve.PointJacobi(curve, x, y, 1, n)
Q1 = numbertheory.inverse_mod(r, n) * (s * R1 + (-e % n) * generator)
Pk1 = Public_key(generator, Q1)
# And the second solution
R2 = ellipticcurve.PointJacobi(curve, x, -y, 1, n)
Q2 = numbertheory.inverse_mod(r, n) * (s * R2 + (-e % n) * generator)
Pk2 = Public_key(generator, Q2)
return [Pk1, Pk2]
class Public_key(object): """Public key for ECDSA."""
def __init__(self, generator, point, verify=True): """Low level ECDSA public key object.
:param generator: the Point that generates the group (the base point)
:param point: the Point that defines the public key
:param bool verify: ifTrue check if point is valid point on curve
:raises InvalidPointError: if the point parameters are invalid or
point does not lay on the curve """
self.curve = generator.curve()
self.generator = generator
self.point = point
n = generator.order()
p = self.curve.p() ifnot (0 <= point.x() < p) ornot (0 <= point.y() < p): raise InvalidPointError( "The public point has x or y out of range."
) if verify andnot self.curve.contains_point(point.x(), point.y()): raise InvalidPointError("Point does not lay on the curve") ifnot n: raise InvalidPointError("Generator point must have order.") # for curve parameters with base point with cofactor 1, all points # that are on the curve are scalar multiples of the base point, so # verifying that is not necessary. See Section 3.2.2.1 of SEC 1 v2 if (
verify and self.curve.cofactor() != 1 andnot n * point == ellipticcurve.INFINITY
): raise InvalidPointError("Generator point order is bad.")
def __eq__(self, other): """Return True if the keys are identical, False otherwise.
Note: for comparison, only placement on the same curve and point
equality is considered, use of the same generator point isnot
considered. """ if isinstance(other, Public_key): return self.curve == other.curve and self.point == other.point return NotImplemented
def __ne__(self, other): """Return False if the keys are identical, True otherwise.""" returnnot self == other
def verifies(self, hash, signature): """Verify that signature is a valid signature of hash. ReturnTrueif the signature is valid. """
# From X9.62 J.3.1.
G = self.generator
n = G.order()
r = signature.r
s = signature.s if r < 1or r > n - 1: returnFalse if s < 1or s > n - 1: returnFalse
c = numbertheory.inverse_mod(s, n)
u1 = (hash * c) % n
u2 = (r * c) % n if hasattr(G, "mul_add"):
xy = G.mul_add(u1, self.point, u2) else:
xy = u1 * G + u2 * self.point
v = xy.x() % n return v == r
class Private_key(object): """Private key for ECDSA."""
def __init__(self, public_key, secret_multiplier): """public_key is of class Public_key;
secret_multiplier is a large integer. """
def __eq__(self, other): """Return True if the points are identical, False otherwise.""" if isinstance(other, Private_key): return (
self.public_key == other.public_key and self.secret_multiplier == other.secret_multiplier
) return NotImplemented
def __ne__(self, other): """Return False if the points are identical, True otherwise.""" returnnot self == other
def sign(self, hash, random_k): """Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
single signature. Also, if an attacker knows a few high-order
bits (or a few low-order bits) of random_k, he can compute our private
key from many signatures. The generation of nonces with adequate
cryptographic strength is very difficult and far beyond the scope
of this comment.
May raise RuntimeError, in which case retrying with a new
random value k isin order. """
G = self.public_key.generator
n = G.order()
k = random_k % n # Fix the bit-length of the random nonce, # so that it doesn't leak via timing. # This does not change that ks = k mod n
ks = k + n
kt = ks + n if bit_length(ks) == bit_length(n):
p1 = kt * G else:
p1 = ks * G
r = p1.x() % n if r == 0: raise RSZeroError("amazingly unlucky random number r")
s = (
numbertheory.inverse_mod(k, n)
* (hash + (self.secret_multiplier * r) % n)
) % n if s == 0: raise RSZeroError("amazingly unlucky random number s") return Signature(r, s)
def int_to_string(x): # pragma: no cover """Convert integer x into a string of bytes, as per X9.62.""" # deprecated in 0.19
warnings.warn( "Function is unused in library code. If you use this code, " "change to util.number_to_string.",
DeprecationWarning,
) assert x >= 0 if x == 0: return b"\0"
result = [] while x:
ordinal = x & 0xFF
result.append(int2byte(ordinal))
x >>= 8
result.reverse() return b"".join(result)
def string_to_int(s): # pragma: no cover """Convert a string of bytes into an integer, as per X9.62.""" # deprecated in 0.19
warnings.warn( "Function is unused in library code. If you use this code, " "change to util.string_to_number.",
DeprecationWarning,
)
result = 0 for c in s: ifnot isinstance(c, int):
c = ord(c)
result = 256 * result + c return result
def digest_integer(m): # pragma: no cover """Convert an integer into a string of bytes, compute
its SHA-1 hash, and convert the result to an integer.""" # deprecated in 0.19
warnings.warn( "Function is unused in library code. If you use this code, " "change to a one-liner with util.number_to_string and " "util.string_to_number methods.",
DeprecationWarning,
) # # I don't expect this function to be used much. I wrote # it in order to be able to duplicate the examples # in ECDSAVS. # from hashlib import sha1
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.