blob: 7066e30099f915507237f940cdfb51c865ea3e82 [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
60class ECDSA256P1(ECDSA256P1Public):
61 """
62 Wrapper around an ECDSA private key.
63 """
64
65 def __init__(self, key):
66 """key should be an instance of EllipticCurvePrivateKey"""
67 self.key = key
68
69 @staticmethod
70 def generate():
71 pk = ec.generate_private_key(
72 ec.SECP256R1(),
73 backend=default_backend())
74 return ECDSA256P1(pk)
75
76 def _get_public(self):
77 return self.key.public_key()
78
79 def export_private(self, path, passwd=None):
80 """Write the private key to the given file, protecting it with the optional password."""
81 if passwd is None:
82 enc = serialization.NoEncryption()
83 else:
84 enc = serialization.BestAvailableEncryption(passwd)
85 pem = self.key.private_bytes(
86 encoding=serialization.Encoding.PEM,
87 format=serialization.PrivateFormat.PKCS8,
88 encryption_algorithm=enc)
89 with open(path, 'wb') as f:
90 f.write(pem)
91
92 def sign(self, payload):
93 return self.key.sign(
94 data=payload,
95 signature_algorithm=ec.ECDSA(SHA256()))