From d7bd92bb665c2cbb6a571898be49eb28c0774b93 Mon Sep 17 00:00:00 2001 From: Alexandre Detiste Date: Mon, 8 Jan 2024 00:17:58 +0100 Subject: [PATCH] reformat with black --- src/ecdsa/_compat.py | 4 +- src/ecdsa/_sha3.py | 1 - src/ecdsa/_version.py | 28 +--- src/ecdsa/curves.py | 32 ++--- src/ecdsa/der.py | 24 +--- src/ecdsa/ecdh.py | 31 ++--- src/ecdsa/ecdsa.py | 34 ++--- src/ecdsa/eddsa.py | 19 +-- src/ecdsa/ellipticcurve.py | 54 ++----- src/ecdsa/keys.py | 55 ++------ src/ecdsa/numbertheory.py | 4 +- src/ecdsa/test_curves.py | 34 ++--- src/ecdsa/test_der.py | 16 +-- src/ecdsa/test_ecdh.py | 15 +- src/ecdsa/test_eddsa.py | 20 +-- src/ecdsa/test_ellipticcurve.py | 20 +-- src/ecdsa/test_jacobi.py | 63 +++------ src/ecdsa/test_keys.py | 28 ++-- src/ecdsa/test_malformed_sigs.py | 28 +--- src/ecdsa/test_numbertheory.py | 19 +-- src/ecdsa/test_pyecdsa.py | 232 +++++++++---------------------- src/ecdsa/util.py | 4 +- versioneer.py | 40 ++---- 23 files changed, 217 insertions(+), 588 deletions(-) diff --git a/src/ecdsa/_compat.py b/src/ecdsa/_compat.py index 4558e33a..031d5cfa 100644 --- a/src/ecdsa/_compat.py +++ b/src/ecdsa/_compat.py @@ -85,9 +85,7 @@ def int_to_bytes(val, length=None, byteorder="big"): (val >> i) & 0xFF for i in reversed(range(0, length * 8, 8)) ) if byteorder == "little": - return bytearray( - (val >> i) & 0xFF for i in range(0, length * 8, 8) - ) + return bytearray((val >> i) & 0xFF for i in range(0, length * 8, 8)) raise ValueError("Only 'big' or 'little' endian supported") else: diff --git a/src/ecdsa/_sha3.py b/src/ecdsa/_sha3.py index 2db00586..abd7b904 100644 --- a/src/ecdsa/_sha3.py +++ b/src/ecdsa/_sha3.py @@ -11,7 +11,6 @@ def shake_256(msg, outlen): return hashlib.new("shake256", msg).digest(outlen) except (TypeError, ValueError): - from ._compat import bytes_to_int, int_to_bytes # From little endian. diff --git a/src/ecdsa/_version.py b/src/ecdsa/_version.py index 8c4354fd..ebfcd527 100644 --- a/src/ecdsa/_version.py +++ b/src/ecdsa/_version.py @@ -68,9 +68,7 @@ def decorate(f): return decorate -def run_command( - commands, args, cwd=None, verbose=False, hide_stderr=False, env=None -): +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None @@ -252,9 +250,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): GITS = ["git.cmd", "git.exe"] TAG_PREFIX_REGEX = r"\*" - _, rc = runner( - GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True - ) + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -289,9 +285,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner( - GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root - ) + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") @@ -340,9 +334,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ( - "unable to parse git-describe output: '%s'" % describe_out - ) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -371,9 +363,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] @@ -461,9 +451,7 @@ def render_pep440_pre(pieces): if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment - tag_version, post_version = pep440_split_post( - pieces["closest-tag"] - ) + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % ( @@ -652,9 +640,7 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords( - get_keywords(), cfg.tag_prefix, verbose - ) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass diff --git a/src/ecdsa/curves.py b/src/ecdsa/curves.py index 38e3a758..2f3ead4e 100644 --- a/src/ecdsa/curves.py +++ b/src/ecdsa/curves.py @@ -78,9 +78,7 @@ def __init__(self, name, curve, generator, oid, openssl_name=None): def __eq__(self, other): if isinstance(other, Curve): - return ( - self.curve == other.curve and self.generator == other.generator - ) + return self.curve == other.curve and self.generator == other.generator return NotImplemented def __ne__(self, other): @@ -109,9 +107,7 @@ def to_der(self, encoding=None, point_encoding="uncompressed"): encoding = "explicit" if encoding not in ("named_curve", "explicit"): - raise ValueError( - "Only 'named_curve' and 'explicit' encodings supported" - ) + raise ValueError("Only 'named_curve' and 'explicit' encodings supported") if encoding == "named_curve": if not self.oid: @@ -163,9 +159,7 @@ def to_pem(self, encoding=None, point_encoding="uncompressed"): :return: PEM encoded ECParameters structure :rtype: str """ - return der.topem( - self.to_der(encoding, point_encoding), "EC PARAMETERS" - ) + return der.topem(self.to_der(encoding, point_encoding), "EC PARAMETERS") @staticmethod def from_der(data, valid_encodings=None): @@ -181,15 +175,11 @@ def from_der(data, valid_encodings=None): if not valid_encodings: valid_encodings = set(("named_curve", "explicit")) if not all(i in ["named_curve", "explicit"] for i in valid_encodings): - raise ValueError( - "Only named_curve and explicit encodings supported" - ) + raise ValueError("Only named_curve and explicit encodings supported") data = normalise_bytes(data) if not der.is_sequence(data): if "named_curve" not in valid_encodings: - raise der.UnexpectedDER( - "named_curve curve parameters not allowed" - ) + raise der.UnexpectedDER("named_curve curve parameters not allowed") oid, empty = der.remove_object(data) if empty: raise der.UnexpectedDER("Unexpected data after OID") @@ -200,9 +190,7 @@ def from_der(data, valid_encodings=None): seq, empty = der.remove_sequence(data) if empty: - raise der.UnexpectedDER( - "Unexpected data after ECParameters structure" - ) + raise der.UnexpectedDER("Unexpected data after ECParameters structure") # decode the ECParameters sequence version, rest = der.remove_integer(seq) if version != 1: @@ -222,9 +210,7 @@ def from_der(data, valid_encodings=None): if field_type == CHARACTERISTIC_TWO_FIELD_OID: raise UnknownCurveError("Characteristic 2 curves unsupported") if field_type != PRIME_FIELD_OID: - raise UnknownCurveError( - "Unknown field type: {0}".format(field_type) - ) + raise UnknownCurveError("Unknown field type: {0}".format(field_type)) prime, empty = der.remove_integer(rest) if empty: raise der.UnexpectedDER( @@ -276,9 +262,7 @@ def from_pem(cls, string, valid_encodings=None): if ec_param_index == -1: raise der.UnexpectedDER("EC PARAMETERS PEM header not found") - return cls.from_der( - der.unpem(string[ec_param_index:]), valid_encodings - ) + return cls.from_der(der.unpem(string[ec_param_index:]), valid_encodings) # the SEC curves diff --git a/src/ecdsa/der.py b/src/ecdsa/der.py index b2914859..151b36eb 100644 --- a/src/ecdsa/der.py +++ b/src/ecdsa/der.py @@ -167,9 +167,7 @@ def remove_octet_string(string): def remove_object(string): if not string: - raise UnexpectedDER( - "Empty string does not encode an object identifier" - ) + raise UnexpectedDER("Empty string does not encode an object identifier") if string[:1] != b"\x06": n = str_idx_as_int(string, 0) raise UnexpectedDER("wanted type 'object' (0x06), got 0x%02x" % n) @@ -200,9 +198,7 @@ def remove_object(string): def remove_integer(string): if not string: - raise UnexpectedDER( - "Empty string is an invalid encoding of an integer" - ) + raise UnexpectedDER("Empty string is an invalid encoding of an integer") if string[:1] != b"\x02": n = str_idx_as_int(string, 0) raise UnexpectedDER("wanted type 'integer' (0x02), got 0x%02x" % n) @@ -223,8 +219,7 @@ def remove_integer(string): smsb = str_idx_as_int(numberbytes, 1) if smsb < 0x80: raise UnexpectedDER( - "Invalid encoding of integer, unnecessary " - "zero padding bytes" + "Invalid encoding of integer, unnecessary " "zero padding bytes" ) return int(binascii.hexlify(numberbytes), 16), rest @@ -324,8 +319,7 @@ def remove_bitstring(string, expect_unused=_sentry): raise UnexpectedDER("Empty string does not encode a bitstring") if expect_unused is _sentry: warnings.warn( - "Legacy call convention used, expect_unused= needs to be" - " specified", + "Legacy call convention used, expect_unused= needs to be" " specified", DeprecationWarning, ) num = str_idx_as_int(string, 0) @@ -390,11 +384,7 @@ def unpem(pem): pem = pem.encode() d = b"".join( - [ - l.strip() - for l in pem.split(b"\n") - if l and not l.startswith(b"-----") - ] + [l.strip() for l in pem.split(b"\n") if l and not l.startswith(b"-----")] ) return base64.b64decode(d) @@ -402,8 +392,6 @@ def unpem(pem): def topem(der, name): b64 = base64.b64encode(compat26_str(der)) lines = [("-----BEGIN %s-----\n" % name).encode()] - lines.extend( - [b64[start : start + 76] + b"\n" for start in range(0, len(b64), 76)] - ) + lines.extend([b64[start : start + 76] + b"\n" for start in range(0, len(b64), 76)]) lines.append(("-----END %s-----\n" % name).encode()) return b"".join(lines) diff --git a/src/ecdsa/ecdh.py b/src/ecdsa/ecdh.py index 7f697d9a..2bd3dc4c 100644 --- a/src/ecdsa/ecdh.py +++ b/src/ecdsa/ecdh.py @@ -76,24 +76,17 @@ def __init__(self, curve=None, private_key=None, public_key=None): def _get_shared_secret(self, remote_public_key): if not self.private_key: - raise NoKeyError( - "Private key needs to be set to create shared secret" - ) + raise NoKeyError("Private key needs to be set to create shared secret") if not self.public_key: - raise NoKeyError( - "Public key needs to be set to create shared secret" - ) - if not ( - self.private_key.curve == self.curve == remote_public_key.curve - ): + raise NoKeyError("Public key needs to be set to create shared secret") + if not (self.private_key.curve == self.curve == remote_public_key.curve): raise InvalidCurveError( "Curves for public key and private key is not equal." ) # shared secret = PUBKEYtheirs * PRIVATEKEYours result = ( - remote_public_key.pubkey.point - * self.private_key.privkey.secret_multiplier + remote_public_key.pubkey.point * self.private_key.privkey.secret_multiplier ) if result == INFINITY: raise InvalidSharedSecretError("Invalid shared secret (INFINITY).") @@ -237,9 +230,7 @@ def load_received_public_key(self, public_key): raise InvalidCurveError("Curve mismatch.") self.public_key = public_key - def load_received_public_key_bytes( - self, public_key_str, valid_encodings=None - ): + def load_received_public_key_bytes(self, public_key_str, valid_encodings=None): """ Load public key from byte string. @@ -256,9 +247,7 @@ def load_received_public_key_bytes( :type valid_encodings: :term:`set-like object` """ return self.load_received_public_key( - VerifyingKey.from_string( - public_key_str, self.curve, valid_encodings - ) + VerifyingKey.from_string(public_key_str, self.curve, valid_encodings) ) def load_received_public_key_der(self, public_key_der): @@ -276,9 +265,7 @@ def load_received_public_key_der(self, public_key_der): :raises InvalidCurveError: public_key curve not the same as self.curve """ - return self.load_received_public_key( - VerifyingKey.from_der(public_key_der) - ) + return self.load_received_public_key(VerifyingKey.from_der(public_key_der)) def load_received_public_key_pem(self, public_key_pem): """ @@ -295,9 +282,7 @@ def load_received_public_key_pem(self, public_key_pem): :raises InvalidCurveError: public_key curve not the same as self.curve """ - return self.load_received_public_key( - VerifyingKey.from_pem(public_key_pem) - ) + return self.load_received_public_key(VerifyingKey.from_pem(public_key_pem)) def generate_sharedsecret_bytes(self): """ diff --git a/src/ecdsa/ecdsa.py b/src/ecdsa/ecdsa.py index 9284ace4..cdecac54 100644 --- a/src/ecdsa/ecdsa.py +++ b/src/ecdsa/ecdsa.py @@ -110,9 +110,7 @@ def recover_public_keys(self, hash, generator): x = r # Compute the curve point with x as x-coordinate - alpha = ( - pow(x, 3, curve.p()) + (curve.a() * x) + curve.b() - ) % curve.p() + 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 == 0 else curve.p() - beta @@ -149,9 +147,7 @@ def __init__(self, generator, point, verify=True): n = generator.order() p = self.curve.p() if not (0 <= point.x() < p) or not (0 <= point.y() < p): - raise InvalidPointError( - "The public point has x or y out of range." - ) + raise InvalidPointError("The public point has x or y out of range.") if verify and not self.curve.contains_point(point.x(), point.y()): raise InvalidPointError("Point does not lay on the curve") if not n: @@ -262,8 +258,7 @@ def sign(self, hash, random_k): if r == 0: raise RSZeroError("amazingly unlucky random number r") s = ( - numbertheory.inverse_mod(k, n) - * (hash + (self.secret_multiplier * r) % n) + numbertheory.inverse_mod(k, n) * (hash + (self.secret_multiplier * r) % n) ) % n if s == 0: raise RSZeroError("amazingly unlucky random number s") @@ -341,8 +336,7 @@ def point_is_valid(generator, x, y): return False if ( curve.cofactor() != 1 - and not n * ellipticcurve.PointJacobi(curve, x, y, 1) - == ellipticcurve.INFINITY + and not n * ellipticcurve.PointJacobi(curve, x, y, 1) == ellipticcurve.INFINITY ): return False return True @@ -447,9 +441,7 @@ def point_is_valid(generator, x, y): ) curve_192 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_192 = ellipticcurve.PointJacobi( - curve_192, _Gx, _Gy, 1, _r, generator=True -) +generator_192 = ellipticcurve.PointJacobi(curve_192, _Gx, _Gy, 1, _r, generator=True) # NIST Curve P-224: @@ -495,9 +487,7 @@ def point_is_valid(generator, x, y): ) curve_224 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_224 = ellipticcurve.PointJacobi( - curve_224, _Gx, _Gy, 1, _r, generator=True -) +generator_224 = ellipticcurve.PointJacobi(curve_224, _Gx, _Gy, 1, _r, generator=True) # NIST Curve P-256: _p = int( @@ -542,9 +532,7 @@ def point_is_valid(generator, x, y): ) curve_256 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_256 = ellipticcurve.PointJacobi( - curve_256, _Gx, _Gy, 1, _r, generator=True -) +generator_256 = ellipticcurve.PointJacobi(curve_256, _Gx, _Gy, 1, _r, generator=True) # NIST Curve P-384: _p = int( @@ -593,9 +581,7 @@ def point_is_valid(generator, x, y): ) curve_384 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_384 = ellipticcurve.PointJacobi( - curve_384, _Gx, _Gy, 1, _r, generator=True -) +generator_384 = ellipticcurve.PointJacobi(curve_384, _Gx, _Gy, 1, _r, generator=True) # NIST Curve P-521: _p = int( @@ -644,9 +630,7 @@ def point_is_valid(generator, x, y): ) curve_521 = ellipticcurve.CurveFp(_p, -3, _b, 1) -generator_521 = ellipticcurve.PointJacobi( - curve_521, _Gx, _Gy, 1, _r, generator=True -) +generator_521 = ellipticcurve.PointJacobi(curve_521, _Gx, _Gy, 1, _r, generator=True) # Certicom secp256-k1 _a = 0x0000000000000000000000000000000000000000000000000000000000000000 diff --git a/src/ecdsa/eddsa.py b/src/ecdsa/eddsa.py index 9769cfd8..9be370df 100644 --- a/src/ecdsa/eddsa.py +++ b/src/ecdsa/eddsa.py @@ -98,15 +98,11 @@ def __init__(self, generator, public_key, public_point=None): if public_point: self.__point = public_point else: - self.__point = ellipticcurve.PointEdwards.from_bytes( - self.curve, public_key - ) + self.__point = ellipticcurve.PointEdwards.from_bytes(self.curve, public_key) def __eq__(self, other): if isinstance(other, PublicKey): - return ( - self.curve == other.curve and self.__encoded == other.__encoded - ) + return self.curve == other.curve and self.__encoded == other.__encoded return NotImplemented def __ne__(self, other): @@ -133,13 +129,9 @@ def verify(self, data, signature): data = compat26_str(data) if len(signature) != 2 * self.baselen: raise ValueError( - "Invalid signature length, expected: {0} bytes".format( - 2 * self.baselen - ) + "Invalid signature length, expected: {0} bytes".format(2 * self.baselen) ) - R = ellipticcurve.PointEdwards.from_bytes( - self.curve, signature[: self.baselen] - ) + R = ellipticcurve.PointEdwards.from_bytes(self.curve, signature[: self.baselen]) S = bytes_to_int(signature[self.baselen :], "little") if S >= self.generator.order(): raise ValueError("Invalid signature") @@ -189,8 +181,7 @@ def private_key(self): def __eq__(self, other): if isinstance(other, PrivateKey): return ( - self.curve == other.curve - and self.__private_key == other.__private_key + self.curve == other.curve and self.__private_key == other.__private_key ) return NotImplemented diff --git a/src/ecdsa/ellipticcurve.py b/src/ecdsa/ellipticcurve.py index 067a149c..ae020acd 100644 --- a/src/ecdsa/ellipticcurve.py +++ b/src/ecdsa/ellipticcurve.py @@ -205,9 +205,7 @@ def __hash__(self): def contains_point(self, x, y): """Is the point (x, y) on this curve?""" - return ( - self.__a * x * x + y * y - 1 - self.__d * x * x * y * y - ) % self.__p == 0 + return (self.__a * x * x + y * y - 1 - self.__d * x * x * y * y) % self.__p == 0 def p(self): return self.__p @@ -296,10 +294,7 @@ def _from_hybrid(cls, data, raw_encoding_length, validate_encoding): # but validate if it's self-consistent if we're asked to do that if validate_encoding and ( - y & 1 - and data[:1] != b"\x07" - or (not y & 1) - and data[:1] != b"\x06" + y & 1 and data[:1] != b"\x07" or (not y & 1) and data[:1] != b"\x06" ): raise MalformedPointError("Inconsistent hybrid point encoding") @@ -323,9 +318,7 @@ def _from_edwards(cls, curve, data): y = mpz(y) x2 = ( - (y * y - 1) - * numbertheory.inverse_mod(curve.d() * y * y - curve.a(), p) - % p + (y * y - 1) * numbertheory.inverse_mod(curve.d() * y * y - curve.a(), p) % p ) try: @@ -341,9 +334,7 @@ def _from_edwards(cls, curve, data): return x, y @classmethod - def from_bytes( - cls, curve, data, validate_encoding=True, valid_encodings=None - ): + def from_bytes(cls, curve, data, validate_encoding=True, valid_encodings=None): """ Initialise the object from byte encoding of a point. @@ -375,16 +366,13 @@ def from_bytes( :rtype: tuple(int, int) """ if not valid_encodings: - valid_encodings = set( - ["uncompressed", "compressed", "hybrid", "raw"] - ) + valid_encodings = set(["uncompressed", "compressed", "hybrid", "raw"]) if not all( i in set(("uncompressed", "compressed", "hybrid", "raw")) for i in valid_encodings ): raise ValueError( - "Only uncompressed, compressed, hybrid or raw encoding " - "supported." + "Only uncompressed, compressed, hybrid or raw encoding " "supported." ) data = normalise_bytes(data) @@ -394,9 +382,7 @@ def from_bytes( key_len = len(data) raw_encoding_length = 2 * orderlen(curve.p()) if key_len == raw_encoding_length and "raw" in valid_encodings: - coord_x, coord_y = cls._from_raw_encoding( - data, raw_encoding_length - ) + coord_x, coord_y = cls._from_raw_encoding(data, raw_encoding_length) elif key_len == raw_encoding_length + 1 and ( "hybrid" in valid_encodings or "uncompressed" in valid_encodings ): @@ -405,16 +391,11 @@ def from_bytes( data, raw_encoding_length, validate_encoding ) elif data[:1] == b"\x04" and "uncompressed" in valid_encodings: - coord_x, coord_y = cls._from_raw_encoding( - data[1:], raw_encoding_length - ) + coord_x, coord_y = cls._from_raw_encoding(data[1:], raw_encoding_length) else: - raise MalformedPointError( - "Invalid X9.62 encoding of the public point" - ) + raise MalformedPointError("Invalid X9.62 encoding of the public point") elif ( - key_len == raw_encoding_length // 2 + 1 - and "compressed" in valid_encodings + key_len == raw_encoding_length // 2 + 1 and "compressed" in valid_encodings ): coord_x, coord_y = cls._from_compressed(data, curve) else: @@ -1190,8 +1171,7 @@ def __add__(self, other): p = self.__curve.p() l = ( - (other.__y - self.__y) - * numbertheory.inverse_mod(other.__x - self.__x, p) + (other.__y - self.__y) * numbertheory.inverse_mod(other.__x - self.__x, p) ) % p x3 = (l * l - self.__x - other.__x) % p @@ -1257,8 +1237,7 @@ def double(self): a = self.__curve.a() l = ( - (3 * self.__x * self.__x + a) - * numbertheory.inverse_mod(2 * self.__y, p) + (3 * self.__x * self.__x + a) * numbertheory.inverse_mod(2 * self.__y, p) ) % p x3 = (l * l - 2 * self.__x) % p @@ -1365,9 +1344,7 @@ def _maybe_precompute(self): coord_x, coord_y, coord_z, coord_t = self.__coords prime = self.__curve.p() - doubler = PointEdwards( - self.__curve, coord_x, coord_y, coord_z, coord_t, order - ) + doubler = PointEdwards(self.__curve, coord_x, coord_y, coord_z, coord_t, order) # for "protection" against Minerva we need 1 or 2 more bits depending # on order bit size, but it's easier to just calculate one # point more always @@ -1481,10 +1458,7 @@ def __add__(self, other): """Add point to another.""" if other == INFINITY: return self - if ( - not isinstance(other, PointEdwards) - or self.__curve != other.__curve - ): + if not isinstance(other, PointEdwards) or self.__curve != other.__curve: raise ValueError("The other point is on a different curve.") p, a = self.__curve.p(), self.__curve.a() diff --git a/src/ecdsa/keys.py b/src/ecdsa/keys.py index f493995d..c18af0f7 100644 --- a/src/ecdsa/keys.py +++ b/src/ecdsa/keys.py @@ -104,9 +104,7 @@ class VerifyingKey(object): def __init__(self, _error__please_use_generate=None): """Unsupported, please use one of the classmethods to initialise.""" if not _error__please_use_generate: - raise TypeError( - "Please use VerifyingKey.generate() to construct me" - ) + raise TypeError("Please use VerifyingKey.generate() to construct me") self.curve = None self.default_hashfunc = None self.pubkey = None @@ -167,9 +165,7 @@ def from_public_point( self.curve = curve self.default_hashfunc = hashfunc try: - self.pubkey = ecdsa.Public_key( - curve.generator, point, validate_point - ) + self.pubkey = ecdsa.Public_key(curve.generator, point, validate_point) except ecdsa.InvalidPointError: raise MalformedPointError("Point does not lay on the curve") self.pubkey.order = curve.order @@ -391,15 +387,13 @@ def from_der( return cls.from_string(point_str, curve, None) if not oid_pk == oid_ecPublicKey: raise der.UnexpectedDER( - "Unexpected object identifier in DER " - "encoding: {0!r}".format(oid_pk) + "Unexpected object identifier in DER " "encoding: {0!r}".format(oid_pk) ) curve = Curve.from_der(rest, valid_curve_encodings) point_str, empty = der.remove_bitstring(point_str_bitstring, 0) if empty != b"": raise der.UnexpectedDER( - "trailing junk after pubkey pointstring: %s" - % binascii.hexlify(empty) + "trailing junk after pubkey pointstring: %s" % binascii.hexlify(empty) ) # raw encoding of point is invalid in DER files if len(point_str) == curve.verifying_key_length: @@ -510,9 +504,7 @@ def from_public_key_recovery_with_digest( sig = ecdsa.Signature(r, s) digest = normalise_bytes(digest) - digest_as_number = _truncate_and_convert_digest( - digest, curve, allow_truncate - ) + digest_as_number = _truncate_and_convert_digest(digest, curve, allow_truncate) pks = sig.recover_public_keys(digest_as_number, generator) # Transforms the ecdsa.Public_key object into a VerifyingKey @@ -544,9 +536,7 @@ def to_string(self, encoding="raw"): assert encoding in ("raw", "uncompressed", "compressed", "hybrid") return self.pubkey.point.to_bytes(encoding) - def to_pem( - self, point_encoding="uncompressed", curve_parameters_encoding=None - ): + def to_pem(self, point_encoding="uncompressed", curve_parameters_encoding=None): """ Convert the public key to the :term:`PEM` format. @@ -575,9 +565,7 @@ def to_pem( "PUBLIC KEY", ) - def to_der( - self, point_encoding="uncompressed", curve_parameters_encoding=None - ): + def to_der(self, point_encoding="uncompressed", curve_parameters_encoding=None): """ Convert the public key to the :term:`DER` format. @@ -788,9 +776,7 @@ def _twisted_edwards_keygen(cls, curve, entropy): private_key = eddsa.PrivateKey(curve.generator, random) public_key = private_key.public_key() - verifying_key = VerifyingKey.from_string( - public_key.public_key(), curve - ) + verifying_key = VerifyingKey.from_string(public_key.public_key(), curve) self = cls(_error__please_use_generate=True) self.curve = curve @@ -1058,8 +1044,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): if der.is_sequence(s): if version not in (0, 1): raise der.UnexpectedDER( - "expected version '0' or '1' at start of privkey, got %d" - % version + "expected version '0' or '1' at start of privkey, got %d" % version ) sequence, s = der.remove_sequence(s) @@ -1067,9 +1052,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): if algorithm_oid in (Ed25519.oid, Ed448.oid): if algorithm_identifier: - raise der.UnexpectedDER( - "Non NULL parameters for a EdDSA key" - ) + raise der.UnexpectedDER("Non NULL parameters for a EdDSA key") key_str_der, s = der.remove_octet_string(s) # As RFC5958 describe, there are may be optional Attributes @@ -1117,8 +1100,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): s, empty = der.remove_sequence(s) if empty != b"": raise der.UnexpectedDER( - "trailing junk after DER privkey: %s" - % binascii.hexlify(empty) + "trailing junk after DER privkey: %s" % binascii.hexlify(empty) ) version, s = der.remove_integer(s) @@ -1126,8 +1108,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): # The version of the ECPrivateKey must be 1. if version != 1: raise der.UnexpectedDER( - "expected version '1' at start of DER privkey, got %d" - % version + "expected version '1' at start of DER privkey, got %d" % version ) privkey_str, s = der.remove_octet_string(s) @@ -1135,9 +1116,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): if not curve: tag, curve_oid_str, s = der.remove_constructed(s) if tag != 0: - raise der.UnexpectedDER( - "expected tag 0 in DER privkey, got %d" % tag - ) + raise der.UnexpectedDER("expected tag 0 in DER privkey, got %d" % tag) curve = Curve.from_der(curve_oid_str, valid_curve_encodings) # we don't actually care about the following fields @@ -1154,9 +1133,7 @@ def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None): # our from_string method likes fixed-length privkey strings if len(privkey_str) < curve.baselen: - privkey_str = ( - b"\x00" * (curve.baselen - len(privkey_str)) + privkey_str - ) + privkey_str = b"\x00" * (curve.baselen - len(privkey_str)) + privkey_str return cls.from_string(privkey_str, curve, hashfunc) def to_string(self): @@ -1268,9 +1245,7 @@ def to_der( ] if format == "ssleay": priv_key_elems.append( - der.encode_constructed( - 0, self.curve.to_der(curve_parameters_encoding) - ) + der.encode_constructed(0, self.curve.to_der(curve_parameters_encoding)) ) # the 0 in encode_bitstring specifies the number of unused bits # in the `encoded_vk` string diff --git a/src/ecdsa/numbertheory.py b/src/ecdsa/numbertheory.py index d3500c70..d43cac14 100644 --- a/src/ecdsa/numbertheory.py +++ b/src/ecdsa/numbertheory.py @@ -64,9 +64,7 @@ def modular_exp(base, exponent, modulus): # pragma: no cover DeprecationWarning, ) if exponent < 0: - raise NegativeExponentError( - "Negative exponents (%d) not allowed" % exponent - ) + raise NegativeExponentError("Negative exponents (%d) not allowed" % exponent) return pow(base, exponent, modulus) diff --git a/src/ecdsa/test_curves.py b/src/ecdsa/test_curves.py index 93b6c9bd..4f68ff7d 100644 --- a/src/ecdsa/test_curves.py +++ b/src/ecdsa/test_curves.py @@ -133,9 +133,7 @@ def test_encoding_to_explicit_compressed_params(self): "AgEB" ) - self.assertEqual( - encoded, bytes(base64.b64decode(compressed_base_point)) - ) + self.assertEqual(encoded, bytes(base64.b64decode(compressed_base_point))) def test_decoding_explicit_from_openssl(self): # generated with openssl 1.1.1k using @@ -223,9 +221,7 @@ def test_decode_malformed_named_curve(self): self.assertIn("Unexpected data after OID", str(e.exception)) def test_decode_malformed_explicit_garbage_after_ECParam(self): - bad_der = bytes( - base64.b64decode(self.base64_params) - ) + der.encode_integer(1) + bad_der = bytes(base64.b64decode(self.base64_params)) + der.encode_integer(1) with self.assertRaises(der.UnexpectedDER) as e: Curve.from_der(bad_der) @@ -244,20 +240,14 @@ def test_decode_malformed_unknown_field_type(self): curve_p = NIST256p.curve.p() bad_der = der.encode_sequence( der.encode_integer(1), - der.encode_sequence( - der.encode_oid(1, 2, 3), der.encode_integer(curve_p) - ), + der.encode_sequence(der.encode_oid(1, 2, 3), der.encode_integer(curve_p)), der.encode_sequence( der.encode_octet_string( number_to_string(NIST256p.curve.a() % curve_p, curve_p) ), - der.encode_octet_string( - number_to_string(NIST256p.curve.b(), curve_p) - ), - ), - der.encode_octet_string( - NIST256p.generator.to_bytes("uncompressed") + der.encode_octet_string(number_to_string(NIST256p.curve.b(), curve_p)), ), + der.encode_octet_string(NIST256p.generator.to_bytes("uncompressed")), der.encode_integer(NIST256p.generator.order()), ) @@ -279,13 +269,9 @@ def test_decode_malformed_garbage_after_prime(self): der.encode_octet_string( number_to_string(NIST256p.curve.a() % curve_p, curve_p) ), - der.encode_octet_string( - number_to_string(NIST256p.curve.b(), curve_p) - ), - ), - der.encode_octet_string( - NIST256p.generator.to_bytes("uncompressed") + der.encode_octet_string(number_to_string(NIST256p.curve.b(), curve_p)), ), + der.encode_octet_string(NIST256p.generator.to_bytes("uncompressed")), der.encode_integer(NIST256p.generator.order()), ) @@ -309,8 +295,7 @@ def test_unknown_curve(self): curve_by_name("foo bar") self.assertIn( - "name 'foo bar' unknown, only curves supported: " - "['NIST192p', 'NIST224p'", + "name 'foo bar' unknown, only curves supported: " "['NIST192p', 'NIST224p'", str(e.exception), ) @@ -319,8 +304,7 @@ def test_with_None_as_parameter(self): curve_by_name(None) self.assertIn( - "name None unknown, only curves supported: " - "['NIST192p', 'NIST224p'", + "name None unknown, only curves supported: " "['NIST192p', 'NIST224p'", str(e.exception), ) diff --git a/src/ecdsa/test_der.py b/src/ecdsa/test_der.py index 0c2dc4d1..31c70b32 100644 --- a/src/ecdsa/test_der.py +++ b/src/ecdsa/test_der.py @@ -136,9 +136,7 @@ def test_old_call_convention(self): der = encode_bitstring(b"\x00\xff") self.assertEqual(len(warns), 1) - self.assertIn( - "unused= needs to be specified", warns[0].message.args[0] - ) + self.assertIn("unused= needs to be specified", warns[0].message.args[0]) self.assertEqual(der, b"\x03\x02\x00\xff") @@ -191,9 +189,7 @@ def test_old_call_convention(self): bits, rest = remove_bitstring(b"\x03\x02\x00\xff") self.assertEqual(len(warns), 1) - self.assertIn( - "expect_unused= needs to be specified", warns[0].message.args[0] - ) + self.assertIn("expect_unused= needs to be specified", warns[0].message.args[0]) self.assertEqual(bits, b"\x00\xff") self.assertEqual(rest, b"") @@ -275,9 +271,7 @@ def test_nist224p_oid(self): self.assertEqual(hexlify(NIST224p.encoded_oid), b"06052b81040021") def test_nist256p_oid(self): - self.assertEqual( - hexlify(NIST256p.encoded_oid), b"06082a8648ce3d030107" - ) + self.assertEqual(hexlify(NIST256p.encoded_oid), b"06082a8648ce3d030107") def test_large_second_subid(self): # from X.690, section 8.19.5 @@ -455,9 +449,7 @@ def st_oid(draw, max_value=2**512, max_size=50): else: second = draw(st.integers(min_value=0, max_value=max_value)) rest = draw( - st.lists( - st.integers(min_value=0, max_value=max_value), max_size=max_size - ) + st.lists(st.integers(min_value=0, max_value=max_value), max_size=max_size) ) return (first, second) + tuple(rest) diff --git a/src/ecdsa/test_ecdh.py b/src/ecdsa/test_ecdh.py index 3395a212..d7bbef7c 100644 --- a/src/ecdsa/test_ecdh.py +++ b/src/ecdsa/test_ecdh.py @@ -138,9 +138,7 @@ def test_ecdh_invalid_shared_secret_curve(): ecdh1 = ECDH(curve=NIST256p) ecdh1.generate_private_key() - ecdh1.load_received_public_key( - SigningKey.generate(NIST256p).get_verifying_key() - ) + ecdh1.load_received_public_key(SigningKey.generate(NIST256p).get_verifying_key()) ecdh1.private_key.privkey.secret_multiplier = ecdh1.private_key.curve.order @@ -361,8 +359,7 @@ def run_openssl(cmd): OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") + c.split(":")[0].strip() for c in run_openssl("ecparam -list_curves").split("\n") ) @@ -391,12 +388,8 @@ def test_ecdh_with_openssl(vcurve): if os.path.isdir("t"): # pragma: no branch shutil.rmtree("t") os.mkdir("t") - run_openssl( - "ecparam -name %s -genkey -out t/privkey1.pem" % vcurve.openssl_name - ) - run_openssl( - "ecparam -name %s -genkey -out t/privkey2.pem" % vcurve.openssl_name - ) + run_openssl("ecparam -name %s -genkey -out t/privkey1.pem" % vcurve.openssl_name) + run_openssl("ecparam -name %s -genkey -out t/privkey2.pem" % vcurve.openssl_name) run_openssl("ec -in t/privkey1.pem -pubout -out t/pubkey1.pem") ecdh1 = ECDH(curve=vcurve) diff --git a/src/ecdsa/test_eddsa.py b/src/ecdsa/test_eddsa.py index 1a35fb32..f6281085 100644 --- a/src/ecdsa/test_eddsa.py +++ b/src/ecdsa/test_eddsa.py @@ -711,8 +711,8 @@ def test_ed25519_mul_precompute_vs_naf(multiple): # TEST 1 ( generator_ed25519, - "9d61b19deffd5a60ba844af492ec2cc4" "4449c5697b326919703bac031cae7f60", - "d75a980182b10ab7d54bfed3c964073a" "0ee172f3daa62325af021a68f707511a", + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "", "e5564300c360ac729086e2cc806e828a" "84877f1eb8e5d974d873e06522490155" @@ -722,8 +722,8 @@ def test_ed25519_mul_precompute_vs_naf(multiple): # TEST 2 ( generator_ed25519, - "4ccd089b28ff96da9db6c346ec114e0f" "5b8a319f35aba624da8cf6ed4fb8a6fb", - "3d4017c3e843895a92b70aa74d1b7ebc" "9c982ccf2ec4968cc0cd55f12af4660c", + "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72", "92a009a9f0d4cab8720e820b5f642540" "a2b27b5416503f8fb3762223ebdb69da" @@ -733,8 +733,8 @@ def test_ed25519_mul_precompute_vs_naf(multiple): # TEST 3 ( generator_ed25519, - "c5aa8df43f9f837bedb7442f31dcb7b1" "66d38535076f094b85ce3a2e0b4458f7", - "fc51cd8e6218a1a38da47ed00230f058" "0816ed13ba3303ac5deb911548908025", + "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82", "6291d657deec24024827e69c3abe01a3" "0ce548a284743a445e3680d7db5ac3ac" @@ -744,8 +744,8 @@ def test_ed25519_mul_precompute_vs_naf(multiple): # TEST 1024 ( generator_ed25519, - "f5e5767cf153319517630f226876b86c" "8160cc583bc013744c6bf255f5cc0ee5", - "278117fc144c72340f67d0f2316e8386" "ceffbf2b2428c9c51fef7c597f1d426e", + "f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5", + "278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e", "08b8b2b733424243760fe426a4b54908" "632110a66c2f6591eabd3345e3e4eb98" "fa6e264bf09efe12ee50f8f54e9f77b1" @@ -818,8 +818,8 @@ def test_ed25519_mul_precompute_vs_naf(multiple): # TEST SHA(abc) ( generator_ed25519, - "833fe62409237b9d62ec77587520911e" "9a759cec1d19755b7da901b96dca3d42", - "ec172b93ad5e563bf4932c70e1245034" "c35467ef2efd4d64ebf819683467e2bf", + "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42", + "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf", "ddaf35a193617abacc417349ae204131" "12e6fa4e89a97ea20a9eeee64b55d39a" "2192992a274fc1a836ba3c23a3feebbd" diff --git a/src/ecdsa/test_ellipticcurve.py b/src/ecdsa/test_ellipticcurve.py index 9fac7eed..dee90823 100644 --- a/src/ecdsa/test_ellipticcurve.py +++ b/src/ecdsa/test_ellipticcurve.py @@ -146,28 +146,18 @@ def test_p192(self): # in X9.62: d = 651056770906015076056810763456358567190100156695615665659 Q = d * self.p192 - self.assertEqual( - Q.x(), 0x62B12D60690CDCF330BABAB6E69763B471F994DD702D16A5 - ) + self.assertEqual(Q.x(), 0x62B12D60690CDCF330BABAB6E69763B471F994DD702D16A5) k = 6140507067065001063065065565667405560006161556565665656654 R = k * self.p192 - self.assertEqual( - R.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - ) - self.assertEqual( - R.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - ) + self.assertEqual(R.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD) + self.assertEqual(R.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835) u1 = 2563697409189434185194736134579731015366492496392189760599 u2 = 6266643813348617967186477710235785849136406323338782220568 temp = u1 * self.p192 + u2 * Q - self.assertEqual( - temp.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD - ) - self.assertEqual( - temp.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835 - ) + self.assertEqual(temp.x(), 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD) + self.assertEqual(temp.y(), 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835) def test_double_infinity(self): p1 = INFINITY diff --git a/src/ecdsa/test_jacobi.py b/src/ecdsa/test_jacobi.py index e52f93bd..81237ed0 100644 --- a/src/ecdsa/test_jacobi.py +++ b/src/ecdsa/test_jacobi.py @@ -209,9 +209,7 @@ def test_compare_double_with_multiply(self): @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1) - ) + st.integers(min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1)) ) def test_multiplications(self, mul): pj = PointJacobi.from_affine(generator_brainpoolp160r1) @@ -224,9 +222,7 @@ def test_multiplications(self, mul): @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1) - ) + st.integers(min_value=0, max_value=int(generator_brainpoolp160r1.order() - 1)) ) @example(0) @example(int(generator_brainpoolp160r1.order())) @@ -242,12 +238,8 @@ def test_precompute(self, mul): @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), ) @example(3, 3) def test_add_scaled_points(self, a_mul, b_mul): @@ -261,12 +253,8 @@ def test_add_scaled_points(self, a_mul, b_mul): @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), st.integers(min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1)), ) def test_add_one_scaled_point(self, a_mul, b_mul, new_z): @@ -294,12 +282,8 @@ def test_add_one_scaled_point(self, a_mul, b_mul, new_z): @pytest.mark.slow @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), st.integers(min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1)), ) @example(1, 1, 1) @@ -360,16 +344,10 @@ def test_add_same_scale_points_static(self): @pytest.mark.slow @settings(**SLOW_SETTINGS) @given( - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), - st.integers( - min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1) - ), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), + st.integers(min_value=1, max_value=int(generator_brainpoolp160r1.order() - 1)), st.lists( - st.integers( - min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1) - ), + st.integers(min_value=1, max_value=int(curve_brainpoolp160r1.p() - 1)), min_size=2, max_size=2, unique=True, @@ -538,12 +516,8 @@ def test_mul_add_precompute_large(self): b = PointJacobi.from_affine(j_g * 255, True) self.assertEqual(j_g * 256, j_g + b) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0 - ) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0) - ) + self.assertEqual(j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0) + self.assertEqual(j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0)) def test_mul_add_to_mul(self): j_g = PointJacobi.from_affine(generator_256) @@ -584,12 +558,8 @@ def test_mul_add_large(self): b = PointJacobi.from_affine(j_g * 255) self.assertEqual(j_g * 256, j_g + b) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0 - ) - self.assertEqual( - j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0) - ) + self.assertEqual(j_g * (0xFF00 + 255 * 0xF0F0), j_g * 0xFF00 + b * 0xF0F0) + self.assertEqual(j_g * (0xFF00 + 255 * 0xF0F0), j_g.mul_add(0xFF00, b, 0xF0F0)) def test_mul_add_with_infinity_as_result(self): j_g = PointJacobi.from_affine(generator_256) @@ -680,8 +650,7 @@ def runner(generator): @pytest.mark.slow @pytest.mark.skipif( - platform.system() == "Windows" - or platform.python_implementation() == "PyPy", + platform.system() == "Windows" or platform.python_implementation() == "PyPy", reason="there are no signals on Windows, and threading breaks coverage" " on PyPy", ) diff --git a/src/ecdsa/test_keys.py b/src/ecdsa/test_keys.py index a41a3dbc..ac82e00f 100644 --- a/src/ecdsa/test_keys.py +++ b/src/ecdsa/test_keys.py @@ -196,9 +196,7 @@ def test_load_key_with_explicit_with_explicit_disabled(self): "-----END PUBLIC KEY-----" ) with self.assertRaises(UnexpectedDER): - VerifyingKey.from_pem( - pub_key_str, valid_curve_encodings=["named_curve"] - ) + VerifyingKey.from_pem(pub_key_str, valid_curve_encodings=["named_curve"]) def test_load_key_with_disabled_format(self): with self.assertRaises(MalformedPointError) as e: @@ -321,9 +319,7 @@ def test_edwards_from_public_key_recovery(self): def test_edwards_from_public_key_recovery_with_digest(self): with self.assertRaises(ValueError) as e: - VerifyingKey.from_public_key_recovery_with_digest( - b"", b"", Ed25519 - ) + VerifyingKey.from_public_key_recovery_with_digest(b"", b"", Ed25519) self.assertIn("unsupported for Edwards", str(e.exception)) @@ -557,9 +553,7 @@ def test_decoding_explicit_curve_parameters_with_explicit_disabled(self): ) with self.assertRaises(UnexpectedDER): - SigningKey.from_pem( - prv_key_str, valid_curve_encodings=["named_curve"] - ) + SigningKey.from_pem(prv_key_str, valid_curve_encodings=["named_curve"]) def test_equality_on_signing_keys(self): sk = SigningKey.from_secret_exponent( @@ -839,12 +833,8 @@ def test_deterministic_sign_that_rises_S_zero_error(self): ) -@pytest.mark.parametrize( - "signature,decoder,mod_apply,fun,vrf_mthd,vrf_data", verifiers -) -def test_VerifyingKey_verify( - signature, decoder, mod_apply, fun, vrf_mthd, vrf_data -): +@pytest.mark.parametrize("signature,decoder,mod_apply,fun,vrf_mthd,vrf_data", verifiers) +def test_VerifyingKey_verify(signature, decoder, mod_apply, fun, vrf_mthd, vrf_data): sig = mod_apply(signature) assert vrf_mthd(sig, fun(vrf_data), sigdecode=decoder) @@ -852,8 +842,7 @@ def test_VerifyingKey_verify( # test SigningKey.from_string() prv_key_bytes = ( - b"^\xc8B\x0b\xd6\xef\x92R\xa9B\xe9\x89\x04<\xa2" - b"\x9fV\x1f\xa5%w\x0e\xb1\xc5" + b"^\xc8B\x0b\xd6\xef\x92R\xa9B\xe9\x89\x04<\xa2" b"\x9fV\x1f\xa5%w\x0e\xb1\xc5" ) assert len(prv_key_bytes) == 24 converters = [] @@ -889,6 +878,7 @@ def test_SigningKey_from_string(convert): key_bytes = unpem(prv_key_str) assert isinstance(key_bytes, bytes) + # last two converters are for array.array of ints, those require input # that's multiple of 4, which no curve we support produces @pytest.mark.parametrize("convert", converters[:-2]) @@ -905,9 +895,7 @@ def test_SigningKey_from_der(convert): @pytest.mark.parametrize("convert", converters) def test_SigningKey_sign_deterministic(convert): - sig = sk.sign_deterministic( - convert(data), extra_entropy=convert(extra_entropy) - ) + sig = sk.sign_deterministic(convert(data), extra_entropy=convert(extra_entropy)) vk.verify(sig, data) diff --git a/src/ecdsa/test_malformed_sigs.py b/src/ecdsa/test_malformed_sigs.py index d7050d2f..2aed0176 100644 --- a/src/ecdsa/test_malformed_sigs.py +++ b/src/ecdsa/test_malformed_sigs.py @@ -47,9 +47,7 @@ """Since the data is hashed for processing, really any string will do.""" -hash_and_size = [ - (name, hashlib.new(name).digest_size) for name in algorithms_available -] +hash_and_size = [(name, hashlib.new(name).digest_size) for name in algorithms_available] """Pairs of hash names and their output sizes. Needed for pairing with curves as we don't support hashes bigger than order sizes of curves.""" @@ -66,9 +64,7 @@ for name, size in sorted(hash_and_size, key=lambda x: x[1]) if 0 < size <= curve.baselen ]: - sk = SigningKey.generate( - curve, hashfunc=partial(hashlib.new, hash_alg) - ) + sk = SigningKey.generate(curve, hashfunc=partial(hashlib.new, hash_alg)) keys_and_sigs.append( ( @@ -85,9 +81,7 @@ [pytest.param(vk, sig, id=name) for name, vk, sig in keys_and_sigs], ) def test_signatures(verifying_key, signature): - assert verifying_key.verify( - signature, example_data, sigdecode=sigdecode_der - ) + assert verifying_key.verify(signature, example_data, sigdecode=sigdecode_der) @st.composite @@ -129,9 +123,7 @@ def st_fuzzed_sig(draw, keys_and_sigs): insert_data = draw(st.binary(max_size=256)) sig = sig[:insert_pos] + insert_data + sig[insert_pos:] - note( - "Inserted at position {0} bytes: {1!r}".format(insert_pos, insert_data) - ) + note("Inserted at position {0} bytes: {1!r}".format(insert_pos, insert_data)) sig = bytes(sig) # make sure that there was performed at least one mutation on the data @@ -273,9 +265,7 @@ def st_der_oid(draw): second = draw(st.integers(min_value=0, max_value=39)) else: second = draw(st.integers(min_value=0, max_value=2**512)) - rest = draw( - st.lists(st.integers(min_value=0, max_value=2**512), max_size=50) - ) + rest = draw(st.lists(st.integers(min_value=0, max_value=2**512), max_size=50)) return encode_oid(first, second, *rest) @@ -296,9 +286,7 @@ def st_der(): | st_der_oid(), lambda children: st.builds(encode_octet_string, st.one_of(children)) | st.builds(lambda x: encode_bitstring(x, 0), st.one_of(children)) - | st.builds( - lambda x: encode_sequence(*x), st.lists(children, max_size=200) - ) + | st.builds(lambda x: encode_sequence(*x), st.lists(children, max_size=200)) | st.builds( encode_constructed, st.integers(min_value=0, max_value=0x3F), @@ -320,9 +308,7 @@ def test_random_der_as_signature(params, der): @settings(**slow_params) @given(st.sampled_from(keys_and_sigs), st.binary(max_size=1024**2)) -@example( - keys_and_sigs[0], encode_sequence(encode_integer(0), encode_integer(0)) -) +@example(keys_and_sigs[0], encode_sequence(encode_integer(0), encode_integer(0))) @example( keys_and_sigs[0], encode_sequence(encode_integer(1), encode_integer(1)) + b"\x00", diff --git a/src/ecdsa/test_numbertheory.py b/src/ecdsa/test_numbertheory.py index 983039e5..0930f22c 100644 --- a/src/ecdsa/test_numbertheory.py +++ b/src/ecdsa/test_numbertheory.py @@ -141,9 +141,7 @@ def st_two_nums_rel_prime(draw): # of breathing space mod = draw(st.integers(min_value=2, max_value=2**1024)) num = draw( - st.integers(min_value=1, max_value=mod - 1).filter( - lambda x: gcd(x, mod) == 1 - ) + st.integers(min_value=1, max_value=mod - 1).filter(lambda x: gcd(x, mod) == 1) ) return num, mod @@ -153,8 +151,7 @@ def st_primes(draw, *args, **kwargs): if "min_value" not in kwargs: # pragma: no branch kwargs["min_value"] = 1 prime = draw( - st.sampled_from(smallprimes) - | st.integers(*args, **kwargs).filter(is_prime) + st.sampled_from(smallprimes) | st.integers(*args, **kwargs).filter(is_prime) ) return prime @@ -172,13 +169,9 @@ def st_comp_with_com_fac(draw): """ Strategy that returns lists of numbers, all having a common factor. """ - primes = draw( - st.lists(st_primes(max_value=2**512), min_size=1, max_size=10) - ) + primes = draw(st.lists(st_primes(max_value=2**512), min_size=1, max_size=10)) # select random prime(s) that will make the common factor of composites - com_fac_primes = draw( - st.lists(st.sampled_from(primes), min_size=1, max_size=20) - ) + com_fac_primes = draw(st.lists(st.sampled_from(primes), min_size=1, max_size=20)) com_fac = reduce(operator.mul, com_fac_primes, 1) # select at most 20 lists (returned numbers), @@ -203,9 +196,7 @@ def st_comp_no_com_fac(draw): Strategy that returns lists of numbers that don't have a common factor. """ primes = draw( - st.lists( - st_primes(max_value=2**512), min_size=2, max_size=10, unique=True - ) + st.lists(st_primes(max_value=2**512), min_size=2, max_size=10, unique=True) ) # first select the primes that will create the uncommon factor # between returned numbers diff --git a/src/ecdsa/test_pyecdsa.py b/src/ecdsa/test_pyecdsa.py index ffa4ab7a..c7d5b727 100644 --- a/src/ecdsa/test_pyecdsa.py +++ b/src/ecdsa/test_pyecdsa.py @@ -116,9 +116,7 @@ def test_deterministic(self): data = b"blahblah" secexp = int("9d0219792467d7d37b4d43298a7d0c05", 16) - priv = SigningKey.from_secret_exponent( - secexp, SECP256k1, hashlib.sha256 - ) + priv = SigningKey.from_secret_exponent(secexp, SECP256k1, hashlib.sha256) pub = priv.get_verifying_key() k = rfc6979.generate_k( @@ -161,9 +159,7 @@ def test_serialize(self): self.assertEqual(secexp1, secexp2) priv1 = SigningKey.from_secret_exponent(secexp1, curve) priv2 = SigningKey.from_secret_exponent(secexp2, curve) - self.assertEqual( - hexlify(priv1.to_string()), hexlify(priv2.to_string()) - ) + self.assertEqual(hexlify(priv1.to_string()), hexlify(priv2.to_string())) self.assertEqual(priv1.to_pem(), priv2.to_pem()) pub1 = priv1.get_verifying_key() pub2 = priv2.get_verifying_key() @@ -306,9 +302,7 @@ def test_pubkey_strings(self): pub2 = VerifyingKey.from_der(pub1_der) self.assertTruePubkeysEqual(pub1, pub2) - self.assertRaises( - der.UnexpectedDER, VerifyingKey.from_der, pub1_der + b"junk" - ) + self.assertRaises(der.UnexpectedDER, VerifyingKey.from_der, pub1_der + b"junk") badpub = VerifyingKey.from_der(pub1_der) class FakeGenerator: @@ -332,9 +326,7 @@ def p(self): pem = pub1.to_pem() self.assertEqual(type(pem), binary_type) self.assertTrue(pem.startswith(b"-----BEGIN PUBLIC KEY-----"), pem) - self.assertTrue( - pem.strip().endswith(b"-----END PUBLIC KEY-----"), pem - ) + self.assertTrue(pem.strip().endswith(b"-----END PUBLIC KEY-----"), pem) pub2 = VerifyingKey.from_pem(pem) self.assertTruePubkeysEqual(pub1, pub2) @@ -367,9 +359,7 @@ def test_sk_to_der_with_invalid_point_encoding(self): def test_vk_from_der_garbage_after_curve_oid(self): type_oid_der = encoded_oid_ecPublicKey - curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) + b( - "garbage" - ) + curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) + b("garbage") enc_type_der = der.encode_sequence(type_oid_der, curve_oid_der) point_der = der.encode_bitstring(b"\x00\xff", None) to_decode = der.encode_sequence(enc_type_der, point_der) @@ -455,9 +445,7 @@ def test_sigencode_string_canonize_no_change(self): s = 400 order = SECP112r1.order - new_r, new_s = sigdecode_string( - sigencode_string_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_string(sigencode_string_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(s, new_s) @@ -467,9 +455,7 @@ def test_sigencode_string_canonize(self): order = SECP112r1.order s = order - 10 - new_r, new_s = sigdecode_string( - sigencode_string_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_string(sigencode_string_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(order - s, new_s) @@ -479,9 +465,7 @@ def test_sigencode_strings_canonize_no_change(self): s = 400 order = SECP112r1.order - new_r, new_s = sigdecode_strings( - sigencode_strings_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_strings(sigencode_strings_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(s, new_s) @@ -491,9 +475,7 @@ def test_sigencode_strings_canonize(self): order = SECP112r1.order s = order - 10 - new_r, new_s = sigdecode_strings( - sigencode_strings_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_strings(sigencode_strings_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(order - s, new_s) @@ -503,9 +485,7 @@ def test_sigencode_der_canonize_no_change(self): s = 200 order = SECP112r1.order - new_r, new_s = sigdecode_der( - sigencode_der_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_der(sigencode_der_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(s, new_s) @@ -515,9 +495,7 @@ def test_sigencode_der_canonize(self): order = SECP112r1.order s = order - 14 - new_r, new_s = sigdecode_der( - sigencode_der_canonize(r, s, order), order - ) + new_r, new_s = sigdecode_der(sigencode_der_canonize(r, s, order), order) self.assertEqual(r, new_r) self.assertEqual(order - s, new_s) @@ -568,9 +546,7 @@ def test_sk_from_der_invalid_const_tag(self): privkey_der = der.encode_octet_string(b"\x00\xff") curve_oid_der = der.encode_oid(*(1, 2, 3)) const_der = der.encode_constructed(1, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) + to_decode = der.encode_sequence(ver_der, privkey_der, const_der, curve_oid_der) with self.assertRaises(der.UnexpectedDER): SigningKey.from_der(to_decode) @@ -580,9 +556,7 @@ def test_sk_from_der_garbage_after_privkey_oid(self): privkey_der = der.encode_octet_string(b"\x00\xff") curve_oid_der = der.encode_oid(*(1, 2, 3)) + b"garbage" const_der = der.encode_constructed(0, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) + to_decode = der.encode_sequence(ver_der, privkey_der, const_der, curve_oid_der) with self.assertRaises(der.UnexpectedDER): SigningKey.from_der(to_decode) @@ -592,9 +566,7 @@ def test_sk_from_der_with_short_privkey(self): privkey_der = der.encode_octet_string(b"\x00\xff") curve_oid_der = der.encode_oid(*(1, 2, 840, 10045, 3, 1, 1)) const_der = der.encode_constructed(0, curve_oid_der) - to_decode = der.encode_sequence( - ver_der, privkey_der, const_der, curve_oid_der - ) + to_decode = der.encode_sequence(ver_der, privkey_der, const_der, curve_oid_der) sk = SigningKey.from_der(to_decode) self.assertEqual(sk.privkey.secret_multiplier, 255) @@ -712,9 +684,7 @@ def test_public_key_recovery(self): signature = sk.sign(data) # Recover verifying keys - recovered_vks = VerifyingKey.from_public_key_recovery( - signature, data, curve - ) + recovered_vks = VerifyingKey.from_public_key_recovery(signature, data, curve) # Test if each pk is valid for recovered_vk in recovered_vks: @@ -723,9 +693,7 @@ def test_public_key_recovery(self): # Test if properties are equal self.assertEqual(vk.curve, recovered_vk.curve) - self.assertEqual( - vk.default_hashfunc, recovered_vk.default_hashfunc - ) + self.assertEqual(vk.default_hashfunc, recovered_vk.default_hashfunc) # Test if original vk is the list of recovered keys self.assertIn( @@ -967,9 +935,7 @@ def test_VerifyingKey_decode_with_small_values(val, even): params = [] for curve in curves: for enc in ["raw", "uncompressed", "compressed", "hybrid"]: - params.append( - pytest.param(curve, enc, id="{0}-{1}".format(curve.name, enc)) - ) + params.append(pytest.param(curve, enc, id="{0}-{1}".format(curve.name, enc))) @pytest.mark.parametrize("curve,encoding", params) @@ -1020,8 +986,7 @@ class OpenSSL(unittest.TestCase): # openssl ec -in privkey.pem -pubout -outform DER -out pubkey.der OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") + c.split(":")[0].strip() for c in run_openssl("ecparam -list_curves").split("\n") ) def get_openssl_messagedigest_arg(self, hash_name): @@ -1268,12 +1233,9 @@ def do_test_from_openssl(self, curve, hash_name="SHA1"): data = b"data" with open("t/data.txt", "wb") as e: e.write(data) + run_openssl("dgst %s -sign t/privkey.pem -out t/data.sig t/data.txt" % mdarg) run_openssl( - "dgst %s -sign t/privkey.pem -out t/data.sig t/data.txt" % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig t/data.txt" - % mdarg + "dgst %s -verify t/pubkey.pem -signature t/data.sig t/data.txt" % mdarg ) with open("t/pubkey.pem", "rb") as e: pubkey_pem = e.read() @@ -1293,9 +1255,7 @@ def do_test_from_openssl(self, curve, hash_name="SHA1"): fp = e.read() sk = SigningKey.from_pem(fp) # 1 sig = sk.sign(data, hashfunc=partial(hashlib.new, hash_name)) - self.assertTrue( - vk.verify(sig, data, hashfunc=partial(hashlib.new, hash_name)) - ) + self.assertTrue(vk.verify(sig, data, hashfunc=partial(hashlib.new, hash_name))) run_openssl( "pkcs8 -topk8 -nocrypt " @@ -1564,47 +1524,37 @@ def do_test_to_openssl(self, curve, hash_name="SHA1"): with open("t/privkey.pem", "wb") as e: e.write(sk.to_pem()) # 2 + run_openssl("dgst %s -sign t/privkey.pem -out t/data.sig2 t/data.txt" % mdarg) run_openssl( - "dgst %s -sign t/privkey.pem -out t/data.sig2 t/data.txt" % mdarg - ) - run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" - % mdarg + "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" % mdarg ) with open("t/privkey-explicit.pem", "wb") as e: e.write(sk.to_pem(curve_parameters_encoding="explicit")) run_openssl( - "dgst %s -sign t/privkey-explicit.pem -out t/data.sig2 t/data.txt" - % mdarg + "dgst %s -sign t/privkey-explicit.pem -out t/data.sig2 t/data.txt" % mdarg ) run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" - % mdarg + "dgst %s -verify t/pubkey.pem -signature t/data.sig2 t/data.txt" % mdarg ) with open("t/privkey-p8.pem", "wb") as e: e.write(sk.to_pem(format="pkcs8")) run_openssl( - "dgst %s -sign t/privkey-p8.pem -out t/data.sig3 t/data.txt" - % mdarg + "dgst %s -sign t/privkey-p8.pem -out t/data.sig3 t/data.txt" % mdarg ) run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" - % mdarg + "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" % mdarg ) with open("t/privkey-p8-explicit.pem", "wb") as e: - e.write( - sk.to_pem(format="pkcs8", curve_parameters_encoding="explicit") - ) + e.write(sk.to_pem(format="pkcs8", curve_parameters_encoding="explicit")) run_openssl( "dgst %s -sign t/privkey-p8-explicit.pem -out t/data.sig3 t/data.txt" % mdarg ) run_openssl( - "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" - % mdarg + "dgst %s -verify t/pubkey.pem -signature t/data.sig3 t/data.txt" % mdarg ) OPENSSL_SUPPORTED_TYPES = set() @@ -1681,13 +1631,9 @@ def do_eddsa_test_from_openssl(self, curve): data = b"data" run_openssl( - "genpkey -algorithm {0} -outform PEM -out t/privkey.pem".format( - curvename - ) - ) - run_openssl( - "pkey -outform PEM -pubout -in t/privkey.pem -out t/pubkey.pem" + "genpkey -algorithm {0} -outform PEM -out t/privkey.pem".format(curvename) ) + run_openssl("pkey -outform PEM -pubout -in t/privkey.pem -out t/pubkey.pem") with open("t/data.txt", "wb") as e: e.write(data) @@ -1726,8 +1672,7 @@ def test_from_openssl_ed448(self): class TooSmallCurve(unittest.TestCase): OPENSSL_SUPPORTED_CURVES = set( - c.split(":")[0].strip() - for c in run_openssl("ecparam -list_curves").split("\n") + c.split(":")[0].strip() for c in run_openssl("ecparam -list_curves").split("\n") ) @pytest.mark.skipif( @@ -1983,9 +1928,7 @@ def test_1(self): ), secexp=int("09A4D6792295A7F730FC3F2B49CBC0F62E862272F", 16), hsh=unhexlify( - b( - "AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF" - ) + b("AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF") ), hash_func=hashlib.sha256, expected=int("23AF4074C90A02B3FE61D286D5C87F425E6BDD81B", 16), @@ -1997,9 +1940,7 @@ def test_2(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha1(b"sample").digest(), hash_func=hashlib.sha1, - expected=int( - "37D7CA00D2C7B0E5E412AC03BD44BA837FDD5B28CD3B0021", 16 - ), + expected=int("37D7CA00D2C7B0E5E412AC03BD44BA837FDD5B28CD3B0021", 16), ) def test_3(self): @@ -2008,9 +1949,7 @@ def test_3(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha256(b"sample").digest(), hash_func=hashlib.sha256, - expected=int( - "32B1B6D7D42A05CB449065727A84804FB1A3E34D8F261496", 16 - ), + expected=int("32B1B6D7D42A05CB449065727A84804FB1A3E34D8F261496", 16), ) def test_4(self): @@ -2019,9 +1958,7 @@ def test_4(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha512(b"sample").digest(), hash_func=hashlib.sha512, - expected=int( - "A2AC7AB055E4F20692D49209544C203A7D1F2C0BFBC75DB1", 16 - ), + expected=int("A2AC7AB055E4F20692D49209544C203A7D1F2C0BFBC75DB1", 16), ) def test_5(self): @@ -2030,9 +1967,7 @@ def test_5(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha1(b"test").digest(), hash_func=hashlib.sha1, - expected=int( - "D9CF9C3D3297D3260773A1DA7418DB5537AB8DD93DE7FA25", 16 - ), + expected=int("D9CF9C3D3297D3260773A1DA7418DB5537AB8DD93DE7FA25", 16), ) def test_6(self): @@ -2041,9 +1976,7 @@ def test_6(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha256(b"test").digest(), hash_func=hashlib.sha256, - expected=int( - "5C4CE89CF56D9E7C77C8585339B006B97B5F0680B4306C6C", 16 - ), + expected=int("5C4CE89CF56D9E7C77C8585339B006B97B5F0680B4306C6C", 16), ) def test_7(self): @@ -2052,9 +1985,7 @@ def test_7(self): secexp=int("6FAB034934E4C0FC9AE67F5B5659A9D7D1FEFD187EE09FD4", 16), hsh=hashlib.sha512(b"test").digest(), hash_func=hashlib.sha512, - expected=int( - "0758753A5254759C7CFBAD2E2D9B0792EEE44136C9480527", 16 - ), + expected=int("0758753A5254759C7CFBAD2E2D9B0792EEE44136C9480527", 16), ) def test_8(self): @@ -2111,10 +2042,7 @@ def _do(self, curve, generator, dA, x_qA, y_qA, dB, x_qB, y_qB, x_Z, y_Z): self.assertEqual(Point(curve, x_qA, y_qA), qA) self.assertEqual(Point(curve, x_qB, y_qB), qB) self.assertTrue( - (dA * qB) - == (dA * dB * generator) - == (dB * dA * generator) - == (dB * qA) + (dA * qB) == (dA * dB * generator) == (dB * dA * generator) == (dB * qA) ) self.assertEqual(Point(curve, x_Z, y_Z), Z) @@ -2126,30 +2054,14 @@ def test_brainpoolP224r1(self): self._do( curve=curve_brainpoolp224r1, generator=BRAINPOOLP224r1.generator, - dA=int( - "7C4B7A2C8A4BAD1FBB7D79CC0955DB7C6A4660CA64CC4778159B495E", 16 - ), - x_qA=int( - "B104A67A6F6E85E14EC1825E1539E8ECDBBF584922367DD88C6BDCF2", 16 - ), - y_qA=int( - "46D782E7FDB5F60CD8404301AC5949C58EDB26BC68BA07695B750A94", 16 - ), - dB=int( - "63976D4AAE6CD0F6DD18DEFEF55D96569D0507C03E74D6486FFA28FB", 16 - ), - x_qB=int( - "2A97089A9296147B71B21A4B574E1278245B536F14D8C2B9D07A874E", 16 - ), - y_qB=int( - "9B900D7C77A709A797276B8CA1BA61BB95B546FC29F862E44D59D25B", 16 - ), - x_Z=int( - "312DFD98783F9FB77B9704945A73BEB6DCCBE3B65D0F967DCAB574EB", 16 - ), - y_Z=int( - "6F800811D64114B1C48C621AB3357CF93F496E4238696A2A012B3C98", 16 - ), + dA=int("7C4B7A2C8A4BAD1FBB7D79CC0955DB7C6A4660CA64CC4778159B495E", 16), + x_qA=int("B104A67A6F6E85E14EC1825E1539E8ECDBBF584922367DD88C6BDCF2", 16), + y_qA=int("46D782E7FDB5F60CD8404301AC5949C58EDB26BC68BA07695B750A94", 16), + dB=int("63976D4AAE6CD0F6DD18DEFEF55D96569D0507C03E74D6486FFA28FB", 16), + x_qB=int("2A97089A9296147B71B21A4B574E1278245B536F14D8C2B9D07A874E", 16), + y_qB=int("9B900D7C77A709A797276B8CA1BA61BB95B546FC29F862E44D59D25B", 16), + x_Z=int("312DFD98783F9FB77B9704945A73BEB6DCCBE3B65D0F967DCAB574EB", 16), + y_Z=int("6F800811D64114B1C48C621AB3357CF93F496E4238696A2A012B3C98", 16), ) def test_brainpoolP256r1(self): @@ -2157,43 +2069,35 @@ def test_brainpoolP256r1(self): curve=curve_brainpoolp256r1, generator=BRAINPOOLP256r1.generator, dA=int( - "041EB8B1E2BC681BCE8E39963B2E9FC415B05283313DD1A8BCC055F11AE" - "49699", + "041EB8B1E2BC681BCE8E39963B2E9FC415B05283313DD1A8BCC055F11AE49699", 16, ), x_qA=int( - "78028496B5ECAAB3C8B6C12E45DB1E02C9E4D26B4113BC4F015F60C5C" - "CC0D206", + "78028496B5ECAAB3C8B6C12E45DB1E02C9E4D26B4113BC4F015F60C5CCC0D206", 16, ), y_qA=int( - "A2AE1762A3831C1D20F03F8D1E3C0C39AFE6F09B4D44BBE80CD100987" - "B05F92B", + "A2AE1762A3831C1D20F03F8D1E3C0C39AFE6F09B4D44BBE80CD100987B05F92B", 16, ), dB=int( - "06F5240EACDB9837BC96D48274C8AA834B6C87BA9CC3EEDD81F99A16B8D" - "804D3", + "06F5240EACDB9837BC96D48274C8AA834B6C87BA9CC3EEDD81F99A16B8D804D3", 16, ), x_qB=int( - "8E07E219BA588916C5B06AA30A2F464C2F2ACFC1610A3BE2FB240B635" - "341F0DB", + "8E07E219BA588916C5B06AA30A2F464C2F2ACFC1610A3BE2FB240B635341F0DB", 16, ), y_qB=int( - "148EA1D7D1E7E54B9555B6C9AC90629C18B63BEE5D7AA6949EBBF47B2" - "4FDE40D", + "148EA1D7D1E7E54B9555B6C9AC90629C18B63BEE5D7AA6949EBBF47B24FDE40D", 16, ), x_Z=int( - "05E940915549E9F6A4A75693716E37466ABA79B4BF2919877A16DD2CC2" - "E23708", + "05E940915549E9F6A4A75693716E37466ABA79B4BF2919877A16DD2CC2E23708", 16, ), y_Z=int( - "6BC23B6702BC5A019438CEEA107DAAD8B94232FFBBC350F3B137628FE6" - "FD134C", + "6BC23B6702BC5A019438CEEA107DAAD8B94232FFBBC350F3B137628FE6FD134C", 16, ), ) @@ -2309,43 +2213,35 @@ def test_brainpoolP256r1(self): curve=curve_brainpoolp256r1, generator=BRAINPOOLP256r1.generator, dA=int( - "81DB1EE100150FF2EA338D708271BE38300CB54241D79950F77B0630398" - "04F1D", + "81DB1EE100150FF2EA338D708271BE38300CB54241D79950F77B063039804F1D", 16, ), x_qA=int( - "44106E913F92BC02A1705D9953A8414DB95E1AAA49E81D9E85F929A8E" - "3100BE5", + "44106E913F92BC02A1705D9953A8414DB95E1AAA49E81D9E85F929A8E3100BE5", 16, ), y_qA=int( - "8AB4846F11CACCB73CE49CBDD120F5A900A69FD32C272223F789EF10E" - "B089BDC", + "8AB4846F11CACCB73CE49CBDD120F5A900A69FD32C272223F789EF10EB089BDC", 16, ), dB=int( - "55E40BC41E37E3E2AD25C3C6654511FFA8474A91A0032087593852D3E7D" - "76BD3", + "55E40BC41E37E3E2AD25C3C6654511FFA8474A91A0032087593852D3E7D76BD3", 16, ), x_qB=int( - "8D2D688C6CF93E1160AD04CC4429117DC2C41825E1E9FCA0ADDD34E6F" - "1B39F7B", + "8D2D688C6CF93E1160AD04CC4429117DC2C41825E1E9FCA0ADDD34E6F1B39F7B", 16, ), y_qB=int( - "990C57520812BE512641E47034832106BC7D3E8DD0E4C7F1136D70065" - "47CEC6A", + "990C57520812BE512641E47034832106BC7D3E8DD0E4C7F1136D7006547CEC6A", 16, ), x_Z=int( - "89AFC39D41D3B327814B80940B042590F96556EC91E6AE7939BCE31F3A" - "18BF2B", + "89AFC39D41D3B327814B80940B042590F96556EC91E6AE7939BCE31F3A18BF2B", 16, ), y_Z=int( - "49C27868F4ECA2179BFD7D59B1E3BF34C1DBDE61AE12931648F43E5963" - "2504DE", + "49C27868F4ECA2179BFD7D59B1E3BF34C1DBDE61AE12931648F43E59632504DE", 16, ), ) diff --git a/src/ecdsa/util.py b/src/ecdsa/util.py index 639bc0c2..aca04827 100644 --- a/src/ecdsa/util.py +++ b/src/ecdsa/util.py @@ -119,9 +119,7 @@ def __call__(self, numbytes): def block_generator(self, seed): counter = 0 while True: - for byte in sha256( - ("prng-%d-%s" % (counter, seed)).encode() - ).digest(): + for byte in sha256(("prng-%d-%s" % (counter, seed)).encode()).digest(): yield byte counter += 1 diff --git a/versioneer.py b/versioneer.py index 81817f1f..62192d51 100644 --- a/versioneer.py +++ b/versioneer.py @@ -404,9 +404,7 @@ def decorate(f): return decorate -def run_command( - commands, args, cwd=None, verbose=False, hide_stderr=False, env=None -): +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None @@ -1205,9 +1203,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): GITS = ["git.cmd", "git.exe"] TAG_PREFIX_REGEX = r"\*" - _, rc = runner( - GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True - ) + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -1242,9 +1238,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner( - GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root - ) + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") @@ -1293,9 +1287,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ( - "unable to parse git-describe output: '%s'" % describe_out - ) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -1324,9 +1316,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] @@ -1446,9 +1436,7 @@ def versions_from_file(filename): def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) - contents = json.dumps( - versions, sort_keys=True, indent=1, separators=(",", ": ") - ) + contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) @@ -1534,9 +1522,7 @@ def render_pep440_pre(pieces): if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment - tag_version, post_version = pep440_split_post( - pieces["closest-tag"] - ) + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % ( @@ -1884,9 +1870,7 @@ def run(self): # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: - target_versionfile = os.path.join( - self.build_lib, cfg.versionfile_build - ) + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) @@ -1913,9 +1897,7 @@ def run(self): return # now locate _version.py in the new build/ directory and replace # it with an updated value - target_versionfile = os.path.join( - self.build_lib, cfg.versionfile_build - ) + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) @@ -2082,9 +2064,7 @@ def do_setup(): configparser.NoOptionError, ) as e: if isinstance(e, (OSError, configparser.NoSectionError)): - print( - "Adding sample versioneer config to setup.cfg", file=sys.stderr - ) + print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr)