blob: f93783de2ba9d5ee5b7dc3b88a279dd60b511a09 [file] [log] [blame]
David Brownb6e0ae62017-11-21 15:13:04 -07001"""
2ECDSA key management
3"""
4
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import serialization
7from cryptography.hazmat.primitives.asymmetric import ec
8from cryptography.hazmat.primitives.hashes import SHA256
9
10from .general import KeyClass
11
12class ECDSAUsageError(Exception):
13 pass
14
15class ECDSA256P1Public(KeyClass):
16 def __init__(self, key):
17 self.key = key
18
19 def shortname(self):
20 return "ecdsa"
21
22 def _unsupported(self, name):
23 raise ECDSAUsageError("Operation {} requires private key".format(name))
24
25 def _get_public(self):
26 return self.key
27
28 def get_public_bytes(self):
29 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
30 return self._get_public().public_bytes(
31 encoding=serialization.Encoding.DER,
32 format=serialization.PublicFormat.SubjectPublicKeyInfo)
33
34 def export_private(self, path, passwd=None):
35 self._unsupported('export_private')
36
37 def export_public(self, path):
38 """Write the public key to the given file."""
39 pem = self._get_public().public_bytes(
40 encoding=serialization.Encoding.PEM,
41 format=serialization.PublicFormat.SubjectPublicKeyInfo)
42 with open(path, 'wb') as f:
43 f.write(pem)
44
45 def sig_type(self):
46 return "ECDSA256_SHA256"
47
48 def sig_tlv(self):
49 return "ECDSA256"
50
51 def sig_len(self):
52 # The DER encoding depends on the high bit, and can be
53 # anywhere from 70 to 72 bytes. Because we have to fill in
54 # the length field before computing the signature, however,
55 # we'll give the largest, and the sig checking code will allow
56 # for it to be up to two bytes larger than the actual
57 # signature.
58 return 72
59
Fabio Utzig4a5477a2019-05-27 15:45:08 -030060 def verify(self, signature, payload):
61 k = self.key
62 if isinstance(self.key, ec.EllipticCurvePrivateKey):
63 k = self.key.public_key()
64 return k.verify(signature=signature, data=payload,
65 signature_algorithm=ec.ECDSA(SHA256()))
66
67
David Brownb6e0ae62017-11-21 15:13:04 -070068class ECDSA256P1(ECDSA256P1Public):
69 """
70 Wrapper around an ECDSA private key.
71 """
72
73 def __init__(self, key):
74 """key should be an instance of EllipticCurvePrivateKey"""
75 self.key = key
76
77 @staticmethod
78 def generate():
79 pk = ec.generate_private_key(
80 ec.SECP256R1(),
81 backend=default_backend())
82 return ECDSA256P1(pk)
83
84 def _get_public(self):
85 return self.key.public_key()
86
87 def export_private(self, path, passwd=None):
88 """Write the private key to the given file, protecting it with the optional password."""
89 if passwd is None:
90 enc = serialization.NoEncryption()
91 else:
92 enc = serialization.BestAvailableEncryption(passwd)
93 pem = self.key.private_bytes(
94 encoding=serialization.Encoding.PEM,
95 format=serialization.PrivateFormat.PKCS8,
96 encryption_algorithm=enc)
97 with open(path, 'wb') as f:
98 f.write(pem)
99
David Brown2c9153a2017-11-21 15:18:12 -0700100 def raw_sign(self, payload):
101 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700102 return self.key.sign(
103 data=payload,
104 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700105
106 def sign(self, payload):
107 # To make fixed length, pad with one or two zeros.
108 sig = self.raw_sign(payload)
109 sig += b'\000' * (self.sig_len() - len(sig))
110 return sig