blob: f17f173907ce59d74bceb245899e12a455310c6a [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001# Copyright 2017 Linaro Limited
Tamas Ban861835c2019-05-13 08:59:38 +01002# Copyright (c) 2017-2019, Arm Limited.
Tamas Banf70ef8c2017-12-19 15:35:09 +00003#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17Cryptographic key management for imgtool.
18"""
19
Gabor Kertesz33e9b232018-09-12 15:38:41 +020020from __future__ import print_function
Tamas Banf70ef8c2017-12-19 15:35:09 +000021from Crypto.Hash import SHA256
22from Crypto.PublicKey import RSA
23from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
Tamas Banf70ef8c2017-12-19 15:35:09 +000024import hashlib
25from pyasn1.type import namedtype, univ
26from pyasn1.codec.der.encoder import encode
27
Tamas Ban861835c2019-05-13 08:59:38 +010028# Sizes that bootutil will recognize
29RSA_KEY_SIZES = [2048, 3072]
30
Tamas Banf70ef8c2017-12-19 15:35:09 +000031# By default, we use RSA-PSS (PKCS 2.1). That can be overridden on
32# the command line to support the older (less secure) PKCS1.5
33sign_rsa_pss = True
34
35AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
36
Tamas Ban861835c2019-05-13 08:59:38 +010037class RSAUsageError(Exception):
38 pass
39
Tamas Banf70ef8c2017-12-19 15:35:09 +000040class RSAPublicKey(univ.Sequence):
41 componentType = namedtype.NamedTypes(
42 namedtype.NamedType('modulus', univ.Integer()),
43 namedtype.NamedType('publicExponent', univ.Integer()))
44
Tamas Ban861835c2019-05-13 08:59:38 +010045class RSAutil():
Tamas Banf70ef8c2017-12-19 15:35:09 +000046 def __init__(self, key):
Tamas Ban861835c2019-05-13 08:59:38 +010047 """Construct an RSA key with the given key data"""
Tamas Banf70ef8c2017-12-19 15:35:09 +000048 self.key = key
49
Tamas Ban861835c2019-05-13 08:59:38 +010050 def key_size(self):
51 return self.key.n.bit_length()
52
Tamas Banf70ef8c2017-12-19 15:35:09 +000053 @staticmethod
Tamas Ban861835c2019-05-13 08:59:38 +010054 def generate(key_size=2048):
55 if key_size not in RSA_KEY_SIZES:
56 raise RSAUsageError("Key size {} is not supported by MCUboot"
57 .format(key_size))
58 return RSAutil(RSA.generate(key_size))
Tamas Banf70ef8c2017-12-19 15:35:09 +000059
60 def export_private(self, path):
61 with open(path, 'wb') as f:
62 f.write(self.key.exportKey('PEM'))
63
64 def get_public_bytes(self):
65 node = RSAPublicKey()
66 node['modulus'] = self.key.n
67 node['publicExponent'] = self.key.e
68 return bytearray(encode(node))
69
70 def emit_c(self):
71 print(AUTOGEN_MESSAGE)
72 print("const unsigned char rsa_pub_key[] = {", end='')
73 encoded = self.get_public_bytes()
74 for count, b in enumerate(encoded):
75 if count % 8 == 0:
76 print("\n\t", end='')
77 else:
78 print(" ", end='')
79 print("0x{:02x},".format(b), end='')
80 print("\n};")
81 print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
82
Tamas Banf70ef8c2017-12-19 15:35:09 +000083 def sig_type(self):
84 """Return the type of this signature (as a string)"""
85 if sign_rsa_pss:
Tamas Ban861835c2019-05-13 08:59:38 +010086 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
Tamas Banf70ef8c2017-12-19 15:35:09 +000087 else:
Tamas Ban861835c2019-05-13 08:59:38 +010088 return "PKCS15_RSA{}_SHA256".format(self.key_size())
Tamas Banf70ef8c2017-12-19 15:35:09 +000089
90 def sig_len(self):
Tamas Ban861835c2019-05-13 08:59:38 +010091 return 256 if self.key_size() == 2048 else 384
Tamas Banf70ef8c2017-12-19 15:35:09 +000092
93 def sig_tlv(self):
Tamas Ban861835c2019-05-13 08:59:38 +010094 return "RSA2048" if self.key_size() == 2048 else "RSA3072"
Tamas Banf70ef8c2017-12-19 15:35:09 +000095
96 def sign(self, payload):
Tamas Ban581034a2017-12-19 19:54:37 +000097 converted_payload = bytes(payload)
98 sha = SHA256.new(converted_payload)
Tamas Banf70ef8c2017-12-19 15:35:09 +000099 if sign_rsa_pss:
100 signer = PKCS1_PSS.new(self.key)
101 else:
102 signer = PKCS1_v1_5.new(self.key)
103 signature = signer.sign(sha)
104 assert len(signature) == self.sig_len()
105 return signature
106
Tamas Banf70ef8c2017-12-19 15:35:09 +0000107def load(path):
108 with open(path, 'rb') as f:
109 pem = f.read()
110 try:
111 key = RSA.importKey(pem)
Tamas Ban861835c2019-05-13 08:59:38 +0100112 return RSAutil(key)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000113 except ValueError:
Tamas Ban581034a2017-12-19 19:54:37 +0000114 raise Exception("Unsupported RSA key file")