blob: 57eb99a54b60382aeb5c96ad4ba41e7bf043294e [file] [log] [blame]
Fabio Utzig8101d1f2019-05-09 15:03:22 -03001"""
2ECDSA key management
3"""
4
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import serialization
7from cryptography.hazmat.primitives.asymmetric import ed25519
8
9from .general import KeyClass
10
11
12class Ed25519UsageError(Exception):
13 pass
14
15
16class Ed25519Public(KeyClass):
17 def __init__(self, key):
18 self.key = key
19
20 def shortname(self):
21 return "ed25519"
22
23 def _unsupported(self, name):
24 raise Ed25519UsageError("Operation {} requires private key".format(name))
25
26 def _get_public(self):
27 return self.key
28
29 def get_public_bytes(self):
30 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
31 return self._get_public().public_bytes(
32 encoding=serialization.Encoding.DER,
33 format=serialization.PublicFormat.SubjectPublicKeyInfo)
34
35 def export_private(self, path, passwd=None):
36 self._unsupported('export_private')
37
38 def export_public(self, path):
39 """Write the public key to the given file."""
40 pem = self._get_public().public_bytes(
41 encoding=serialization.Encoding.PEM,
42 format=serialization.PublicFormat.SubjectPublicKeyInfo)
43 with open(path, 'wb') as f:
44 f.write(pem)
45
46 def sig_type(self):
47 return "ED25519"
48
49 def sig_tlv(self):
50 return "ED25519"
51
52 def sig_len(self):
53 return 64
54
55
56class Ed25519(Ed25519Public):
57 """
58 Wrapper around an ECDSA private key.
59 """
60
61 def __init__(self, key):
62 """key should be an instance of EllipticCurvePrivateKey"""
63 self.key = key
64
65 @staticmethod
66 def generate():
67 pk = ed25519.Ed25519PrivateKey.generate()
68 return Ed25519(pk)
69
70 def _get_public(self):
71 return self.key.public_key()
72
73 def export_private(self, path, passwd=None):
74 """
75 Write the private key to the given file, protecting it with the
76 optional password.
77 """
78 if passwd is None:
79 enc = serialization.NoEncryption()
80 else:
81 enc = serialization.BestAvailableEncryption(passwd)
82 pem = self.key.private_bytes(
83 encoding=serialization.Encoding.PEM,
84 format=serialization.PrivateFormat.PKCS8,
85 encryption_algorithm=enc)
86 with open(path, 'wb') as f:
87 f.write(pem)
88
89 def sign_digest(self, digest):
90 """Return the actual signature"""
91 return self.key.sign(data=digest)
92
93 def verify_digest(self, signature, digest):
94 """Verify that signature is valid for given digest"""
95 k = self.key
96 if isinstance(self.key, ed25519.Ed25519PrivateKey):
97 k = self.key.public_key()
98 return k.verify(signature=signature, data=digest)