blob: 8d5d048382c7be1de6e53048b15d743c2913fb5d [file] [log] [blame]
David Brown5e7c6dd2017-11-16 14:47:16 -07001"""
2RSA Key management
3"""
4
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import serialization
7from cryptography.hazmat.primitives.asymmetric import rsa
8from cryptography.hazmat.primitives.asymmetric.padding import PSS, MGF1
9from cryptography.hazmat.primitives.hashes import SHA256
10
11from .general import KeyClass
12
13class RSAUsageError(Exception):
14 pass
15
16class RSA2048Public(KeyClass):
17 """The public key can only do a few operations"""
18 def __init__(self, key):
19 self.key = key
20
21 def shortname(self):
22 return "rsa"
23
24 def _unsupported(self, name):
25 raise RSAUsageError("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 embedded into MCUboot is in PKCS1 format.
32 return self._get_public().public_bytes(
33 encoding=serialization.Encoding.DER,
34 format=serialization.PublicFormat.PKCS1)
35
36 def export_private(self, path, passwd=None):
37 self._unsupported('export_private')
38
39 def export_public(self, path):
40 """Write the public key to the given file."""
41 pem = self._get_public().public_bytes(
42 encoding=serialization.Encoding.PEM,
43 format=serialization.PublicFormat.SubjectPublicKeyInfo)
44 with open(path, 'wb') as f:
45 f.write(pem)
46
47 def sig_type(self):
48 return "PKCS1_PSS_RSA2048_SHA256"
49
50 def sig_tlv(self):
51 return "RSA2048"
52
53class RSA2048(RSA2048Public):
54 """
55 Wrapper around an 2048-bit RSA key, with imgtool support.
56 """
57
58 def __init__(self, key):
59 """The key should be a private key from cryptography"""
60 self.key = key
61
62 @staticmethod
63 def generate():
64 pk = rsa.generate_private_key(
65 public_exponent=65537,
66 key_size=2048,
67 backend=default_backend())
68 return RSA2048(pk)
69
70 def _get_public(self):
71 return self.key.public_key()
72
73 def export_private(self, path, passwd=None):
74 """Write the private key to the given file, protecting it with the optional password."""
75 if passwd is None:
76 enc = serialization.NoEncryption()
77 else:
78 enc = serialization.BestAvailableEncryption(passwd)
79 pem = self.key.private_bytes(
80 encoding=serialization.Encoding.PEM,
81 format=serialization.PrivateFormat.PKCS8,
82 encryption_algorithm=enc)
83 with open(path, 'wb') as f:
84 f.write(pem)
85
86 def sign(self, payload):
87 return self.key.sign(
88 data=payload,
89 padding=PSS(mgf=MGF1(SHA256()), salt_length=PSS.MAX_LENGTH),
90 algorithm=SHA256())