blob: e45492b36a188be9f7ddc060e65224e443d89da0 [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
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020036 def get_private_bytes(self, minimal):
37 self._unsupported('get_private_bytes')
38
David Brownb6e0ae62017-11-21 15:13:04 -070039 def export_private(self, path, passwd=None):
40 self._unsupported('export_private')
41
42 def export_public(self, path):
43 """Write the public key to the given file."""
44 pem = self._get_public().public_bytes(
45 encoding=serialization.Encoding.PEM,
46 format=serialization.PublicFormat.SubjectPublicKeyInfo)
47 with open(path, 'wb') as f:
48 f.write(pem)
49
50 def sig_type(self):
51 return "ECDSA256_SHA256"
52
53 def sig_tlv(self):
54 return "ECDSA256"
55
56 def sig_len(self):
David Brown4878c272020-03-10 16:23:56 -060057 # Early versions of MCUboot (< v1.5.0) required ECDSA
58 # signatures to be padded to 72 bytes. Because the DER
59 # encoding is done with signed integers, the size of the
60 # signature will vary depending on whether the high bit is set
61 # in each value. This padding was done in a
62 # not-easily-reversible way (by just adding zeros).
63 #
64 # The signing code no longer requires this padding, and newer
65 # versions of MCUboot don't require it. But, continue to
66 # return the total length so that the padding can be done if
67 # requested.
David Brownb6e0ae62017-11-21 15:13:04 -070068 return 72
69
Fabio Utzig4a5477a2019-05-27 15:45:08 -030070 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080071 # strip possible paddings added during sign
72 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030073 k = self.key
74 if isinstance(self.key, ec.EllipticCurvePrivateKey):
75 k = self.key.public_key()
76 return k.verify(signature=signature, data=payload,
77 signature_algorithm=ec.ECDSA(SHA256()))
78
79
David Brownb6e0ae62017-11-21 15:13:04 -070080class ECDSA256P1(ECDSA256P1Public):
81 """
82 Wrapper around an ECDSA private key.
83 """
84
85 def __init__(self, key):
86 """key should be an instance of EllipticCurvePrivateKey"""
87 self.key = key
David Brown4878c272020-03-10 16:23:56 -060088 self.pad_sig = False
David Brownb6e0ae62017-11-21 15:13:04 -070089
90 @staticmethod
91 def generate():
92 pk = ec.generate_private_key(
93 ec.SECP256R1(),
94 backend=default_backend())
95 return ECDSA256P1(pk)
96
97 def _get_public(self):
98 return self.key.public_key()
99
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200100 def _build_minimal_ecdsa_privkey(self, der):
101 '''
102 Builds a new DER that only includes the EC private key, removing the
103 public key that is added as an "optional" BITSTRING.
104 '''
105 offset_PUB = 68
106 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
107 if der[offset_PUB] != 0xa1:
108 raise ECDSAUsageError(EXCEPTION_TEXT)
109 len_PUB = der[offset_PUB + 1]
110 b = bytearray(der[:-offset_PUB])
111 offset_SEQ = 29
112 if b[offset_SEQ] != 0x30:
113 raise ECDSAUsageError(EXCEPTION_TEXT)
114 b[offset_SEQ + 1] -= len_PUB
115 offset_OCT_STR = 27
116 if b[offset_OCT_STR] != 0x04:
117 raise ECDSAUsageError(EXCEPTION_TEXT)
118 b[offset_OCT_STR + 1] -= len_PUB
119 if b[0] != 0x30 or b[1] != 0x81:
120 raise ECDSAUsageError(EXCEPTION_TEXT)
121 b[2] -= len_PUB
122 return b
123
124 def get_private_bytes(self, minimal):
125 priv = self.key.private_bytes(
126 encoding=serialization.Encoding.DER,
127 format=serialization.PrivateFormat.PKCS8,
128 encryption_algorithm=serialization.NoEncryption())
129 if minimal:
130 priv = self._build_minimal_ecdsa_privkey(priv)
131 return priv
132
David Brownb6e0ae62017-11-21 15:13:04 -0700133 def export_private(self, path, passwd=None):
134 """Write the private key to the given file, protecting it with the optional password."""
135 if passwd is None:
136 enc = serialization.NoEncryption()
137 else:
138 enc = serialization.BestAvailableEncryption(passwd)
139 pem = self.key.private_bytes(
140 encoding=serialization.Encoding.PEM,
141 format=serialization.PrivateFormat.PKCS8,
142 encryption_algorithm=enc)
143 with open(path, 'wb') as f:
144 f.write(pem)
145
David Brown2c9153a2017-11-21 15:18:12 -0700146 def raw_sign(self, payload):
147 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700148 return self.key.sign(
149 data=payload,
150 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700151
152 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700153 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600154 if self.pad_sig:
155 # To make fixed length, pad with one or two zeros.
156 sig += b'\000' * (self.sig_len() - len(sig))
157 return sig
158 else:
159 return sig