Skip to content

Commit 5fbeeaf

Browse files
committed
Use new public hash and scheme methods to SSlibKey
* Add public methods to return hash algorithm name and padding for all supported SSlibKey schemes, if applicable. * Use in relevant signers * Remove obsolete helpers in those signers Signed-off-by: Lukas Puehringer <[email protected]>
1 parent 48c7523 commit 5fbeeaf

File tree

4 files changed

+47
-53
lines changed

4 files changed

+47
-53
lines changed

securesystemslib/signer/_azure_signer.py

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def __init__(self, az_key_uri: str, public_key: SSlibKey):
9999
self.signature_algorithm = self._get_signature_algorithm(
100100
public_key.scheme,
101101
)
102-
self.hash_algorithm = self._get_hash_algorithm(public_key)
102+
self.hash_algorithm = public_key.get_hash_algorithm_name()
103103
self._public_key = public_key
104104

105105
@property
@@ -150,23 +150,6 @@ def _get_signature_algorithm(scheme: str) -> SignatureAlgorithm:
150150
"""Return SignatureAlgorithm after parsing the public key"""
151151
return SIGNATURE_ALGORITHMS[scheme]
152152

153-
@staticmethod
154-
def _get_hash_algorithm(public_key: Key) -> str:
155-
"""Return the hash algorithm used by the public key"""
156-
# Format is "ecdsa-sha2-nistp256"
157-
comps = public_key.scheme.split("-")
158-
if len(comps) != 3: # noqa: PLR2004
159-
raise UnsupportedKeyType("Invalid scheme found")
160-
161-
if comps[2] == "nistp256":
162-
return "sha256"
163-
if comps[2] == "nistp384":
164-
return "sha384"
165-
if comps[2] == "nistp521":
166-
return "sha512"
167-
168-
raise UnsupportedKeyType("Unsupported curve supplied by key")
169-
170153
@staticmethod
171154
def _get_keytype_and_scheme(crv: str) -> tuple[str, str]:
172155
try:

securesystemslib/signer/_crypto_signer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,12 @@ def __init__(
140140
if not isinstance(private_key, RSAPrivateKey):
141141
raise ValueError(f"invalid rsa key: {type(private_key)}")
142142

143-
padding_name, hash_name = public_key.scheme.split("-")[1:]
143+
hash_name = public_key.get_hash_algorithm_name()
144144
hash_algo = get_hash_algorithm(hash_name)
145+
146+
padding_name = public_key.get_padding_name()
145147
padding = _get_rsa_padding(padding_name, hash_algo)
148+
146149
self._sign_args = _RSASignArgs(padding, hash_algo)
147150
self._private_key = private_key
148151

securesystemslib/signer/_gcp_signer.py

Lines changed: 1 addition & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def __init__(self, gcp_keyid: str, public_key: SSlibKey):
109109
f"in key {public_key.keyid}"
110110
)
111111

112-
self.hash_algorithm = self._get_hash_algorithm(public_key)
112+
self.hash_algorithm = public_key.get_hash_algorithm_name()
113113
self.gcp_keyid = gcp_keyid
114114
self._public_key = public_key
115115
self.client = kms.KeyManagementServiceClient()
@@ -166,38 +166,6 @@ def _get_keytype_and_scheme(algorithm: int) -> tuple[str, str]:
166166
"""Return keytype and scheme for the KMS algorithm enum"""
167167
return KEYTYPES_AND_SCHEMES[algorithm]
168168

169-
@staticmethod
170-
def _get_hash_algorithm(public_key: Key) -> str:
171-
"""Helper function to return payload hash algorithm used for this key"""
172-
173-
# TODO: This could be a public abstract method on Key so that GCPSigner
174-
# would not be tied to a specific Key implementation -- not all keys
175-
# have a pre hash algorithm though.
176-
if public_key.keytype == "rsa":
177-
# hash algorithm is encoded as last scheme portion
178-
algo = public_key.scheme.split("-")[-1]
179-
elif public_key.keytype in [
180-
"ecdsa",
181-
"ecdsa-sha2-nistp256",
182-
"ecdsa-sha2-nistp384",
183-
]:
184-
# nistp256 uses sha-256, nistp384 uses sha-384
185-
bits = public_key.scheme.split("-nistp")[-1]
186-
algo = f"sha{bits}"
187-
else:
188-
raise exceptions.UnsupportedAlgorithmError(
189-
f"Unsupported key type {public_key.keytype} in key {public_key.keyid}"
190-
)
191-
192-
# trigger UnsupportedAlgorithm if appropriate
193-
# TODO: deduplicate scheme parsing and improve validation (#594, #766)
194-
try:
195-
_ = hashlib.new(algo)
196-
except (ValueError, TypeError) as e:
197-
raise exceptions.UnsupportedAlgorithmError(algo) from e
198-
199-
return algo
200-
201169
def sign(self, payload: bytes) -> Signature:
202170
"""Signs payload with Google Cloud KMS.
203171

securesystemslib/signer/_key.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,45 @@ def __init__(
218218
raise ValueError(f"public key string required for scheme {scheme}")
219219
super().__init__(keyid, keytype, scheme, keyval, unrecognized_fields)
220220

221+
def get_hash_algorithm_name(self) -> str:
222+
"""Get hash algorithm name for scheme. Raise
223+
ValueError if the scheme is not a supported pre-hash scheme."""
224+
if self.scheme in [
225+
"rsassa-pss-sha224",
226+
"rsassa-pss-sha256",
227+
"rsassa-pss-sha384",
228+
"rsassa-pss-sha512",
229+
"rsa-pkcs1v15-sha224",
230+
"rsa-pkcs1v15-sha256",
231+
"rsa-pkcs1v15-sha384",
232+
"rsa-pkcs1v15-sha512",
233+
"ecdsa-sha2-nistp256",
234+
"ecdsa-sha2-nistp384",
235+
]:
236+
return f"sha{self.scheme[-3:]}"
237+
238+
elif self.scheme == "ecdsa-sha2-nistp521":
239+
return "sha512"
240+
241+
raise ValueError(f"method not supported for scheme {self.scheme}")
242+
243+
def get_padding_name(self) -> str:
244+
"""Get padding name for scheme. Raise
245+
ValueError if the scheme is not a supported padded rsa scheme."""
246+
if self.scheme in [
247+
"rsassa-pss-sha224",
248+
"rsassa-pss-sha256",
249+
"rsassa-pss-sha384",
250+
"rsassa-pss-sha512",
251+
"rsa-pkcs1v15-sha224",
252+
"rsa-pkcs1v15-sha256",
253+
"rsa-pkcs1v15-sha384",
254+
"rsa-pkcs1v15-sha512",
255+
]:
256+
return self.scheme.split("-")[1]
257+
258+
raise ValueError(f"method not supported for scheme {self.scheme}")
259+
221260
@classmethod
222261
def from_dict(cls, keyid: str, key_dict: dict[str, Any]) -> SSlibKey:
223262
keytype, scheme, keyval = cls._from_dict(key_dict)
@@ -358,8 +397,9 @@ def _validate_curve(
358397
]:
359398
key = cast(RSAPublicKey, self._crypto_key())
360399
_validate_type(key, RSAPublicKey)
361-
padding_name, hash_name = self.scheme.split("-")[1:]
400+
hash_name = self.get_hash_algorithm_name()
362401
hash_algorithm = get_hash_algorithm(hash_name)
402+
padding_name = self.get_padding_name()
363403
padding = self._get_rsa_padding(padding_name, hash_algorithm)
364404
key.verify(signature, data, padding, hash_algorithm)
365405

0 commit comments

Comments
 (0)