| 31 | |
| 32 | |
| 33 | class CryptographyECKey(Key): |
| 34 | SHA256 = hashes.SHA256 |
| 35 | SHA384 = hashes.SHA384 |
| 36 | SHA512 = hashes.SHA512 |
| 37 | |
| 38 | def __init__(self, key, algorithm, cryptography_backend=default_backend): |
| 39 | if algorithm not in ALGORITHMS.EC: |
| 40 | raise JWKError("hash_alg: %s is not a valid hash algorithm" % algorithm) |
| 41 | |
| 42 | self.hash_alg = { |
| 43 | ALGORITHMS.ES256: self.SHA256, |
| 44 | ALGORITHMS.ES384: self.SHA384, |
| 45 | ALGORITHMS.ES512: self.SHA512, |
| 46 | }.get(algorithm) |
| 47 | self._algorithm = algorithm |
| 48 | |
| 49 | self.cryptography_backend = cryptography_backend |
| 50 | |
| 51 | if hasattr(key, "public_bytes") or hasattr(key, "private_bytes"): |
| 52 | self.prepared_key = key |
| 53 | return |
| 54 | |
| 55 | if hasattr(key, "to_pem"): |
| 56 | # convert to PEM and let cryptography below load it as PEM |
| 57 | key = key.to_pem().decode("utf-8") |
| 58 | |
| 59 | if isinstance(key, dict): |
| 60 | self.prepared_key = self._process_jwk(key) |
| 61 | return |
| 62 | |
| 63 | if isinstance(key, str): |
| 64 | key = key.encode("utf-8") |
| 65 | |
| 66 | if isinstance(key, bytes): |
| 67 | # Attempt to load key. We don't know if it's |
| 68 | # a Public Key or a Private Key, so we try |
| 69 | # the Public Key first. |
| 70 | try: |
| 71 | try: |
| 72 | key = load_pem_public_key(key, self.cryptography_backend()) |
| 73 | except ValueError: |
| 74 | key = load_pem_private_key(key, password=None, backend=self.cryptography_backend()) |
| 75 | except Exception as e: |
| 76 | raise JWKError(e) |
| 77 | |
| 78 | self.prepared_key = key |
| 79 | return |
| 80 | |
| 81 | raise JWKError("Unable to parse an ECKey from key: %s" % key) |
| 82 | |
| 83 | def _process_jwk(self, jwk_dict): |
| 84 | if not jwk_dict.get("kty") == "EC": |
| 85 | raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get("kty")) |
| 86 | |
| 87 | if not all(k in jwk_dict for k in ["x", "y", "crv"]): |
| 88 | raise JWKError("Mandatory parameters are missing") |
| 89 | |
| 90 | x = base64_to_long(jwk_dict.get("x")) |
no outgoing calls
searching dependent graphs…