MCPcopy
hub / github.com/jpadilla/pyjwt / prepare_key

Method prepare_key

jwt/algorithms.py:641–672  ·  view source on GitHub ↗
(self, key: AllowedECKeys | str | bytes)

Source from the content-addressed store, hash-verified

639 )
640
641 def prepare_key(self, key: AllowedECKeys | str | bytes) -> AllowedECKeys:
642 if isinstance(key, self._crypto_key_types):
643 # See note in RSAAlgorithm.prepare_key.
644 ec_key = cast(AllowedECKeys, key) # type: ignore[redundant-cast,unused-ignore]
645 self._validate_curve(ec_key)
646 return ec_key
647
648 if not isinstance(key, (bytes, str)):
649 raise TypeError("Expecting a PEM-formatted key.")
650
651 key_bytes = force_bytes(key)
652
653 # Attempt to load key. We don't know if it's
654 # a Signing Key or a Verifying Key, so we try
655 # the Verifying Key first.
656 try:
657 if key_bytes.startswith(b"ecdsa-sha2-"):
658 public_key: PublicKeyTypes = load_ssh_public_key(key_bytes)
659 else:
660 public_key = load_pem_public_key(key_bytes)
661
662 # Explicit check the key to prevent confusing errors from cryptography
663 self.check_crypto_key_type(public_key)
664 ec_public_key = cast(EllipticCurvePublicKey, public_key)
665 self._validate_curve(ec_public_key)
666 return ec_public_key
667 except ValueError:
668 private_key = load_pem_private_key(key_bytes, password=None)
669 self.check_crypto_key_type(private_key)
670 ec_private_key = cast(EllipticCurvePrivateKey, private_key)
671 self._validate_curve(ec_private_key)
672 return ec_private_key
673
674 def sign(self, msg: bytes, key: EllipticCurvePrivateKey) -> bytes:
675 der_sig = key.sign(msg, ECDSA(self.hash_alg()))

Calls 3

_validate_curveMethod · 0.95
force_bytesFunction · 0.85
check_crypto_key_typeMethod · 0.80