blob: 9198bb499bf628f535a7a685f7ae51747ccb6ddb [file] [log] [blame]
David Brownb6e0ae62017-11-21 15:13:04 -07001"""
2ECDSA key management
3"""
4
David Brown79c4fcf2021-01-26 15:04:05 -07005# SPDX-License-Identifier: Apache-2.0
6
David Brownb6e0ae62017-11-21 15:13:04 -07007from cryptography.hazmat.backends import default_backend
8from cryptography.hazmat.primitives import serialization
9from cryptography.hazmat.primitives.asymmetric import ec
10from cryptography.hazmat.primitives.hashes import SHA256
11
12from .general import KeyClass
13
14class ECDSAUsageError(Exception):
15 pass
16
17class ECDSA256P1Public(KeyClass):
18 def __init__(self, key):
19 self.key = key
20
21 def shortname(self):
22 return "ecdsa"
23
24 def _unsupported(self, name):
25 raise ECDSAUsageError("Operation {} requires private key".format(name))
26
27 def _get_public(self):
28 return self.key
29
30 def get_public_bytes(self):
31 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
32 return self._get_public().public_bytes(
33 encoding=serialization.Encoding.DER,
34 format=serialization.PublicFormat.SubjectPublicKeyInfo)
35
Fabio Utzig6f286772022-09-04 20:03:11 -030036 def get_public_pem(self):
37 return self._get_public().public_bytes(
38 encoding=serialization.Encoding.PEM,
39 format=serialization.PublicFormat.SubjectPublicKeyInfo)
40
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020041 def get_private_bytes(self, minimal):
42 self._unsupported('get_private_bytes')
43
David Brownb6e0ae62017-11-21 15:13:04 -070044 def export_private(self, path, passwd=None):
45 self._unsupported('export_private')
46
47 def export_public(self, path):
48 """Write the public key to the given file."""
49 pem = self._get_public().public_bytes(
50 encoding=serialization.Encoding.PEM,
51 format=serialization.PublicFormat.SubjectPublicKeyInfo)
52 with open(path, 'wb') as f:
53 f.write(pem)
54
55 def sig_type(self):
56 return "ECDSA256_SHA256"
57
58 def sig_tlv(self):
59 return "ECDSA256"
60
61 def sig_len(self):
David Brown4878c272020-03-10 16:23:56 -060062 # Early versions of MCUboot (< v1.5.0) required ECDSA
63 # signatures to be padded to 72 bytes. Because the DER
64 # encoding is done with signed integers, the size of the
65 # signature will vary depending on whether the high bit is set
66 # in each value. This padding was done in a
67 # not-easily-reversible way (by just adding zeros).
68 #
69 # The signing code no longer requires this padding, and newer
70 # versions of MCUboot don't require it. But, continue to
71 # return the total length so that the padding can be done if
72 # requested.
David Brownb6e0ae62017-11-21 15:13:04 -070073 return 72
74
Fabio Utzig4a5477a2019-05-27 15:45:08 -030075 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080076 # strip possible paddings added during sign
77 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030078 k = self.key
79 if isinstance(self.key, ec.EllipticCurvePrivateKey):
80 k = self.key.public_key()
81 return k.verify(signature=signature, data=payload,
82 signature_algorithm=ec.ECDSA(SHA256()))
83
84
David Brownb6e0ae62017-11-21 15:13:04 -070085class ECDSA256P1(ECDSA256P1Public):
86 """
87 Wrapper around an ECDSA private key.
88 """
89
90 def __init__(self, key):
91 """key should be an instance of EllipticCurvePrivateKey"""
92 self.key = key
David Brown4878c272020-03-10 16:23:56 -060093 self.pad_sig = False
David Brownb6e0ae62017-11-21 15:13:04 -070094
95 @staticmethod
96 def generate():
97 pk = ec.generate_private_key(
98 ec.SECP256R1(),
99 backend=default_backend())
100 return ECDSA256P1(pk)
101
102 def _get_public(self):
103 return self.key.public_key()
104
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200105 def _build_minimal_ecdsa_privkey(self, der):
106 '''
107 Builds a new DER that only includes the EC private key, removing the
108 public key that is added as an "optional" BITSTRING.
109 '''
110 offset_PUB = 68
111 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
112 if der[offset_PUB] != 0xa1:
113 raise ECDSAUsageError(EXCEPTION_TEXT)
114 len_PUB = der[offset_PUB + 1]
115 b = bytearray(der[:-offset_PUB])
116 offset_SEQ = 29
117 if b[offset_SEQ] != 0x30:
118 raise ECDSAUsageError(EXCEPTION_TEXT)
119 b[offset_SEQ + 1] -= len_PUB
120 offset_OCT_STR = 27
121 if b[offset_OCT_STR] != 0x04:
122 raise ECDSAUsageError(EXCEPTION_TEXT)
123 b[offset_OCT_STR + 1] -= len_PUB
124 if b[0] != 0x30 or b[1] != 0x81:
125 raise ECDSAUsageError(EXCEPTION_TEXT)
126 b[2] -= len_PUB
127 return b
128
129 def get_private_bytes(self, minimal):
130 priv = self.key.private_bytes(
131 encoding=serialization.Encoding.DER,
132 format=serialization.PrivateFormat.PKCS8,
133 encryption_algorithm=serialization.NoEncryption())
134 if minimal:
135 priv = self._build_minimal_ecdsa_privkey(priv)
136 return priv
137
David Brownb6e0ae62017-11-21 15:13:04 -0700138 def export_private(self, path, passwd=None):
139 """Write the private key to the given file, protecting it with the optional password."""
140 if passwd is None:
141 enc = serialization.NoEncryption()
142 else:
143 enc = serialization.BestAvailableEncryption(passwd)
144 pem = self.key.private_bytes(
145 encoding=serialization.Encoding.PEM,
146 format=serialization.PrivateFormat.PKCS8,
147 encryption_algorithm=enc)
148 with open(path, 'wb') as f:
149 f.write(pem)
150
David Brown2c9153a2017-11-21 15:18:12 -0700151 def raw_sign(self, payload):
152 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700153 return self.key.sign(
154 data=payload,
155 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700156
157 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700158 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600159 if self.pad_sig:
160 # To make fixed length, pad with one or two zeros.
161 sig += b'\000' * (self.sig_len() - len(sig))
162 return sig
163 else:
164 return sig