Debian Codegraph @

dns/dnssecalgs/base.py

raw
1 from abc import ABC, abstractmethod # pylint: disable=no-name-in-module
2 from typing import Any, Type
3
4 import dns.rdataclass
5 import dns.rdatatype
6 from dns.dnssectypes import Algorithm
7 from dns.exception import AlgorithmKeyMismatch
8 from dns.rdtypes.ANY.DNSKEY import DNSKEY
9 from dns.rdtypes.dnskeybase import Flag
10
11
12 class GenericPublicKey(ABC):
13 algorithm: Algorithm
14
15 @abstractmethod
16 def __init__(self, key: Any) -> None:
17 pass
18
19 @abstractmethod
20 def verify(self, signature: bytes, data: bytes) -> None:
21 """Verify signed DNSSEC data"""
22
23 @abstractmethod
24 def encode_key_bytes(self) -> bytes:
25 """Encode key as bytes for DNSKEY"""
26
27 @classmethod
28 def _ensure_algorithm_key_combination(cls, key: DNSKEY) -> None:
29 if key.algorithm != cls.algorithm:
30 raise AlgorithmKeyMismatch
31
32 def to_dnskey(self, flags: int = Flag.ZONE, protocol: int = 3) -> DNSKEY:
33 """Return public key as DNSKEY"""
34 return DNSKEY(
35 rdclass=dns.rdataclass.IN,
36 rdtype=dns.rdatatype.DNSKEY,
37 flags=flags,
38 protocol=protocol,
39 algorithm=self.algorithm,
40 key=self.encode_key_bytes(),
41 )
42
43 @classmethod
44 @abstractmethod
45 def from_dnskey(cls, key: DNSKEY) -> "GenericPublicKey":
46 """Create public key from DNSKEY"""
47
48 @classmethod
49 @abstractmethod
50 def from_pem(cls, public_pem: bytes) -> "GenericPublicKey":
51 """Create public key from PEM-encoded SubjectPublicKeyInfo as specified
52 in RFC 5280"""
53
54 @abstractmethod
55 def to_pem(self) -> bytes:
56 """Return public-key as PEM-encoded SubjectPublicKeyInfo as specified
57 in RFC 5280"""
58
59
60 class GenericPrivateKey(ABC):
61 public_cls: Type[GenericPublicKey]
62
63 @abstractmethod
64 def __init__(self, key: Any) -> None:
65 pass
66
67 @abstractmethod
68 def sign(
69 self,
70 data: bytes,
71 verify: bool = False,
72 deterministic: bool = True,
73 ) -> bytes:
74 """Sign DNSSEC data"""
75
76 @abstractmethod
77 def public_key(self) -> "GenericPublicKey":
78 """Return public key instance"""
79
80 @classmethod
81 @abstractmethod
82 def from_pem(
83 cls, private_pem: bytes, password: bytes | None = None
84 ) -> "GenericPrivateKey":
85 """Create private key from PEM-encoded PKCS#8"""
86
87 @abstractmethod
88 def to_pem(self, password: bytes | None = None) -> bytes:
89 """Return private key as PEM-encoded PKCS#8"""