Skip to content

Commit d5016ae

Browse files
committed
Refactor hash algo check in GCPSigner
Minimally refactor EAFP to LBYL to avoid clunky re-raise. Signed-off-by: Lukas Puehringer <[email protected]>
1 parent f5f162f commit d5016ae

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

securesystemslib/signer/_gcp_signer.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -163,29 +163,22 @@ def _get_hash_algorithm(public_key: Key) -> str:
163163
# TODO: This could be a public abstract method on Key so that GCPSigner
164164
# would not be tied to a specific Key implementation -- not all keys
165165
# have a pre hash algorithm though.
166-
if public_key.keytype == "rsa":
167-
# hash algorithm is encoded as last scheme portion
168-
algo = public_key.scheme.split("-")[-1]
169-
elif public_key.keytype in [
170-
"ecdsa",
171-
"ecdsa-sha2-nistp256",
172-
"ecdsa-sha2-nistp384",
173-
]:
166+
if (
167+
public_key.keytype == "rsa" and public_key.scheme.endswith(("256", "512"))
168+
) or (
174169
# nistp256 uses sha-256, nistp384 uses sha-384
175-
bits = public_key.scheme.split("-nistp")[-1]
176-
algo = f"sha{bits}"
170+
# TODO: Check for invalid type/scheme combinations (#766)
171+
public_key.keytype
172+
in ["ecdsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"]
173+
and public_key.scheme.endswith(("256", "384"))
174+
):
175+
algo = public_key.scheme[-3:]
177176
else:
178177
raise exceptions.UnsupportedAlgorithmError(
179-
f"Unsupported key type {public_key.keytype} in key {public_key.keyid}"
178+
f"Unsupported {public_key.keytype}/{public_key.scheme} "
179+
f"(type/scheme) in key {public_key.keyid}"
180180
)
181181

182-
# trigger UnsupportedAlgorithm if appropriate
183-
# TODO: validate scheme/algo in constructor (#766)
184-
try:
185-
_ = hashlib.new(algo)
186-
except (ValueError, TypeError) as e:
187-
raise exceptions.UnsupportedAlgorithmError(algo) from e
188-
189182
return algo
190183

191184
def sign(self, payload: bytes) -> Signature:

0 commit comments

Comments
 (0)