Skip to content

Commit

Permalink
reformat with black
Browse files Browse the repository at this point in the history
  • Loading branch information
a-detiste committed Jan 7, 2024
1 parent b5d2389 commit d7bd92b
Show file tree
Hide file tree
Showing 23 changed files with 217 additions and 588 deletions.
4 changes: 1 addition & 3 deletions src/ecdsa/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 0 additions & 1 deletion src/ecdsa/_sha3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
28 changes: 7 additions & 21 deletions src/ecdsa/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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" % (
Expand Down Expand Up @@ -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

Expand Down
32 changes: 8 additions & 24 deletions src/ecdsa/curves.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand All @@ -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")
Expand All @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down
24 changes: 6 additions & 18 deletions src/ecdsa/der.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -390,20 +384,14 @@ 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)


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)
31 changes: 8 additions & 23 deletions src/ecdsa/ecdh.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).")
Expand Down Expand Up @@ -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.
Expand All @@ -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):
Expand All @@ -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):
"""
Expand All @@ -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):
"""
Expand Down
Loading

0 comments on commit d7bd92b

Please sign in to comment.