| 1 |
from typing import Any, Type |
| 2 |
|
| 3 |
from cryptography.hazmat.primitives import serialization |
| 4 |
|
| 5 |
from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey |
| 6 |
from dns.exception import AlgorithmKeyMismatch |
| 7 |
|
| 8 |
|
| 9 |
class CryptographyPublicKey(GenericPublicKey): |
| 10 |
key: Any = None |
| 11 |
key_cls: Any = None |
| 12 |
|
| 13 |
def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called |
| 14 |
if self.key_cls is None: |
| 15 |
raise TypeError("Undefined private key class") |
| 16 |
if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type |
| 17 |
key, self.key_cls |
| 18 |
): |
| 19 |
raise AlgorithmKeyMismatch |
| 20 |
self.key = key |
| 21 |
|
| 22 |
@classmethod |
| 23 |
def from_pem(cls, public_pem: bytes) -> "GenericPublicKey": |
| 24 |
key = serialization.load_pem_public_key(public_pem) |
| 25 |
return cls(key=key) |
| 26 |
|
| 27 |
def to_pem(self) -> bytes: |
| 28 |
return self.key.public_bytes( |
| 29 |
encoding=serialization.Encoding.PEM, |
| 30 |
format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
class CryptographyPrivateKey(GenericPrivateKey): |
| 35 |
key: Any = None |
| 36 |
key_cls: Any = None |
| 37 |
public_cls: Type[CryptographyPublicKey] # pyright: ignore |
| 38 |
|
| 39 |
def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called |
| 40 |
if self.key_cls is None: |
| 41 |
raise TypeError("Undefined private key class") |
| 42 |
if not isinstance( # pylint: disable=isinstance-second-argument-not-valid-type |
| 43 |
key, self.key_cls |
| 44 |
): |
| 45 |
raise AlgorithmKeyMismatch |
| 46 |
self.key = key |
| 47 |
|
| 48 |
def public_key(self) -> "CryptographyPublicKey": |
| 49 |
return self.public_cls(key=self.key.public_key()) |
| 50 |
|
| 51 |
@classmethod |
| 52 |
def from_pem( |
| 53 |
cls, private_pem: bytes, password: bytes | None = None |
| 54 |
) -> "GenericPrivateKey": |
| 55 |
key = serialization.load_pem_private_key(private_pem, password=password) |
| 56 |
return cls(key=key) |
| 57 |
|
| 58 |
def to_pem(self, password: bytes | None = None) -> bytes: |
| 59 |
encryption_algorithm: serialization.KeySerializationEncryption |
| 60 |
if password: |
| 61 |
encryption_algorithm = serialization.BestAvailableEncryption(password) |
| 62 |
else: |
| 63 |
encryption_algorithm = serialization.NoEncryption() |
| 64 |
return self.key.private_bytes( |
| 65 |
encoding=serialization.Encoding.PEM, |
| 66 |
format=serialization.PrivateFormat.PKCS8, |
| 67 |
encryption_algorithm=encryption_algorithm, |
| 68 |
) |