blob: 1fe805e1881cc116d565ee5da7af5f69f8f9386a [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
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020034 def get_private_bytes(self, minimal):
35 self._unsupported('get_private_bytes')
36
David Brownb6e0ae62017-11-21 15:13:04 -070037 def export_private(self, path, passwd=None):
38 self._unsupported('export_private')
39
40 def export_public(self, path):
41 """Write the public key to the given file."""
42 pem = self._get_public().public_bytes(
43 encoding=serialization.Encoding.PEM,
44 format=serialization.PublicFormat.SubjectPublicKeyInfo)
45 with open(path, 'wb') as f:
46 f.write(pem)
47
48 def sig_type(self):
49 return "ECDSA256_SHA256"
50
51 def sig_tlv(self):
52 return "ECDSA256"
53
54 def sig_len(self):
55 # The DER encoding depends on the high bit, and can be
56 # anywhere from 70 to 72 bytes. Because we have to fill in
57 # the length field before computing the signature, however,
58 # we'll give the largest, and the sig checking code will allow
59 # for it to be up to two bytes larger than the actual
60 # signature.
61 return 72
62
Fabio Utzig4a5477a2019-05-27 15:45:08 -030063 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080064 # strip possible paddings added during sign
65 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030066 k = self.key
67 if isinstance(self.key, ec.EllipticCurvePrivateKey):
68 k = self.key.public_key()
69 return k.verify(signature=signature, data=payload,
70 signature_algorithm=ec.ECDSA(SHA256()))
71
72
David Brownb6e0ae62017-11-21 15:13:04 -070073class ECDSA256P1(ECDSA256P1Public):
74 """
75 Wrapper around an ECDSA private key.
76 """
77
78 def __init__(self, key):
79 """key should be an instance of EllipticCurvePrivateKey"""
80 self.key = key
81
82 @staticmethod
83 def generate():
84 pk = ec.generate_private_key(
85 ec.SECP256R1(),
86 backend=default_backend())
87 return ECDSA256P1(pk)
88
89 def _get_public(self):
90 return self.key.public_key()
91
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020092 def _build_minimal_ecdsa_privkey(self, der):
93 '''
94 Builds a new DER that only includes the EC private key, removing the
95 public key that is added as an "optional" BITSTRING.
96 '''
97 offset_PUB = 68
98 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
99 if der[offset_PUB] != 0xa1:
100 raise ECDSAUsageError(EXCEPTION_TEXT)
101 len_PUB = der[offset_PUB + 1]
102 b = bytearray(der[:-offset_PUB])
103 offset_SEQ = 29
104 if b[offset_SEQ] != 0x30:
105 raise ECDSAUsageError(EXCEPTION_TEXT)
106 b[offset_SEQ + 1] -= len_PUB
107 offset_OCT_STR = 27
108 if b[offset_OCT_STR] != 0x04:
109 raise ECDSAUsageError(EXCEPTION_TEXT)
110 b[offset_OCT_STR + 1] -= len_PUB
111 if b[0] != 0x30 or b[1] != 0x81:
112 raise ECDSAUsageError(EXCEPTION_TEXT)
113 b[2] -= len_PUB
114 return b
115
116 def get_private_bytes(self, minimal):
117 priv = self.key.private_bytes(
118 encoding=serialization.Encoding.DER,
119 format=serialization.PrivateFormat.PKCS8,
120 encryption_algorithm=serialization.NoEncryption())
121 if minimal:
122 priv = self._build_minimal_ecdsa_privkey(priv)
123 return priv
124
David Brownb6e0ae62017-11-21 15:13:04 -0700125 def export_private(self, path, passwd=None):
126 """Write the private key to the given file, protecting it with the optional password."""
127 if passwd is None:
128 enc = serialization.NoEncryption()
129 else:
130 enc = serialization.BestAvailableEncryption(passwd)
131 pem = self.key.private_bytes(
132 encoding=serialization.Encoding.PEM,
133 format=serialization.PrivateFormat.PKCS8,
134 encryption_algorithm=enc)
135 with open(path, 'wb') as f:
136 f.write(pem)
137
David Brown2c9153a2017-11-21 15:18:12 -0700138 def raw_sign(self, payload):
139 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700140 return self.key.sign(
141 data=payload,
142 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700143
144 def sign(self, payload):
145 # To make fixed length, pad with one or two zeros.
146 sig = self.raw_sign(payload)
147 sig += b'\000' * (self.sig_len() - len(sig))
148 return sig