blob: 6c6f60fb78b79507e76391c918eabbaadf2db641 [file] [log] [blame]
Fabio Utzig960b4c52020-04-02 13:07:12 -03001"""
2X25519 key management
3"""
4
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import serialization
7from cryptography.hazmat.primitives.asymmetric import x25519
8
9from .general import KeyClass
10
11
12class X25519UsageError(Exception):
13 pass
14
15
16class X25519Public(KeyClass):
17 def __init__(self, key):
18 self.key = key
19
20 def shortname(self):
21 return "x25519"
22
23 def _unsupported(self, name):
24 raise X25519UsageError("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 get_private_bytes(self, minimal):
36 self._unsupported('get_private_bytes')
37
38 def export_private(self, path, passwd=None):
39 self._unsupported('export_private')
40
41 def export_public(self, path):
42 """Write the public key to the given file."""
43 pem = self._get_public().public_bytes(
44 encoding=serialization.Encoding.PEM,
45 format=serialization.PublicFormat.SubjectPublicKeyInfo)
46 with open(path, 'wb') as f:
47 f.write(pem)
48
49 def sig_type(self):
50 return "X25519"
51
52 def sig_tlv(self):
53 return "X25519"
54
55 def sig_len(self):
56 return 32
57
58
59class X25519(X25519Public):
60 """
61 Wrapper around an X25519 private key.
62 """
63
64 def __init__(self, key):
65 """key should be an instance of EllipticCurvePrivateKey"""
66 self.key = key
67
68 @staticmethod
69 def generate():
70 pk = x25519.X25519PrivateKey.generate()
71 return X25519(pk)
72
73 def _get_public(self):
74 return self.key.public_key()
75
76 def get_private_bytes(self, minimal):
77 raise X25519UsageError("Operation not supported with {} keys".format(
78 self.shortname()))
79
80 def export_private(self, path, passwd=None):
81 """
82 Write the private key to the given file, protecting it with the
83 optional password.
84 """
85 if passwd is None:
86 enc = serialization.NoEncryption()
87 else:
88 enc = serialization.BestAvailableEncryption(passwd)
89 pem = self.key.private_bytes(
90 encoding=serialization.Encoding.PEM,
91 format=serialization.PrivateFormat.PKCS8,
92 encryption_algorithm=enc)
93 with open(path, 'wb') as f:
94 f.write(pem)
95
96 def sign_digest(self, digest):
97 """Return the actual signature"""
98 return self.key.sign(data=digest)
99
100 def verify_digest(self, signature, digest):
101 """Verify that signature is valid for given digest"""
102 k = self.key
103 if isinstance(self.key, x25519.X25519PrivateKey):
104 k = self.key.public_key()
105 return k.verify(signature=signature, data=digest)