| 1 |
from typing import Type |
| 2 |
|
| 3 |
from cryptography.hazmat.primitives import serialization |
| 4 |
from cryptography.hazmat.primitives.asymmetric import ed448, ed25519 |
| 5 |
|
| 6 |
from dns.dnssecalgs.cryptography import CryptographyPrivateKey, CryptographyPublicKey |
| 7 |
from dns.dnssectypes import Algorithm |
| 8 |
from dns.rdtypes.ANY.DNSKEY import DNSKEY |
| 9 |
|
| 10 |
|
| 11 |
class PublicEDDSA(CryptographyPublicKey): |
| 12 |
def verify(self, signature: bytes, data: bytes) -> None: |
| 13 |
self.key.verify(signature, data) |
| 14 |
|
| 15 |
def encode_key_bytes(self) -> bytes: |
| 16 |
"""Encode a public key per RFC 8080, section 3.""" |
| 17 |
return self.key.public_bytes( |
| 18 |
encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw |
| 19 |
) |
| 20 |
|
| 21 |
@classmethod |
| 22 |
def from_dnskey(cls, key: DNSKEY) -> "PublicEDDSA": |
| 23 |
cls._ensure_algorithm_key_combination(key) |
| 24 |
return cls( |
| 25 |
key=cls.key_cls.from_public_bytes(key.key), |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
class PrivateEDDSA(CryptographyPrivateKey): |
| 30 |
public_cls: Type[PublicEDDSA] # pyright: ignore |
| 31 |
|
| 32 |
def sign( |
| 33 |
self, |
| 34 |
data: bytes, |
| 35 |
verify: bool = False, |
| 36 |
deterministic: bool = True, |
| 37 |
) -> bytes: |
| 38 |
"""Sign using a private key per RFC 8080, section 4.""" |
| 39 |
signature = self.key.sign(data) |
| 40 |
if verify: |
| 41 |
self.public_key().verify(signature, data) |
| 42 |
return signature |
| 43 |
|
| 44 |
@classmethod |
| 45 |
def generate(cls) -> "PrivateEDDSA": |
| 46 |
return cls(key=cls.key_cls.generate()) |
| 47 |
|
| 48 |
|
| 49 |
class PublicED25519(PublicEDDSA): |
| 50 |
key: ed25519.Ed25519PublicKey |
| 51 |
key_cls = ed25519.Ed25519PublicKey |
| 52 |
algorithm = Algorithm.ED25519 |
| 53 |
|
| 54 |
|
| 55 |
class PrivateED25519(PrivateEDDSA): |
| 56 |
key: ed25519.Ed25519PrivateKey |
| 57 |
key_cls = ed25519.Ed25519PrivateKey |
| 58 |
public_cls = PublicED25519 |
| 59 |
|
| 60 |
|
| 61 |
class PublicED448(PublicEDDSA): |
| 62 |
key: ed448.Ed448PublicKey |
| 63 |
key_cls = ed448.Ed448PublicKey |
| 64 |
algorithm = Algorithm.ED448 |
| 65 |
|
| 66 |
|
| 67 |
class PrivateED448(PrivateEDDSA): |
| 68 |
key: ed448.Ed448PrivateKey |
| 69 |
key_cls = ed448.Ed448PrivateKey |
| 70 |
public_cls = PublicED448 |