| 442 | return None |
| 443 | |
| 444 | def prepare_key(self, key: AllowedRSAKeys | str | bytes) -> AllowedRSAKeys: |
| 445 | if isinstance(key, self._crypto_key_types): |
| 446 | # Cast is required for type narrowing on Python 3.9's mypy |
| 447 | # but redundant on newer mypy versions; suppress both |
| 448 | # diagnostics so the line works across all supported envs. |
| 449 | return cast(AllowedRSAKeys, key) # type: ignore[redundant-cast,unused-ignore] |
| 450 | |
| 451 | if not isinstance(key, (bytes, str)): |
| 452 | raise TypeError("Expecting a PEM-formatted key.") |
| 453 | |
| 454 | key_bytes = force_bytes(key) |
| 455 | |
| 456 | try: |
| 457 | if key_bytes.startswith(b"ssh-rsa"): |
| 458 | public_key: PublicKeyTypes = load_ssh_public_key(key_bytes) |
| 459 | self.check_crypto_key_type(public_key) |
| 460 | return cast(RSAPublicKey, public_key) |
| 461 | else: |
| 462 | private_key: PrivateKeyTypes = load_pem_private_key( |
| 463 | key_bytes, password=None |
| 464 | ) |
| 465 | self.check_crypto_key_type(private_key) |
| 466 | return cast(RSAPrivateKey, private_key) |
| 467 | except ValueError: |
| 468 | try: |
| 469 | public_key = load_pem_public_key(key_bytes) |
| 470 | self.check_crypto_key_type(public_key) |
| 471 | return cast(RSAPublicKey, public_key) |
| 472 | except (ValueError, UnsupportedAlgorithm): |
| 473 | raise InvalidKeyError( |
| 474 | "Could not parse the provided public key." |
| 475 | ) from None |
| 476 | |
| 477 | @overload |
| 478 | @staticmethod |