blob: 9728cd064e47af91e1e99cb9434f84025648a661 [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001# Copyright 2017 Linaro Limited
Tamas Ban581034a2017-12-19 19:54:37 +00002# Copyright (c) 2017, 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
20from Crypto.Hash import SHA256
21from Crypto.PublicKey import RSA
22from Crypto.Signature import PKCS1_v1_5, PKCS1_PSS
Tamas Banf70ef8c2017-12-19 15:35:09 +000023import hashlib
24from pyasn1.type import namedtype, univ
25from pyasn1.codec.der.encoder import encode
26
27# By default, we use RSA-PSS (PKCS 2.1). That can be overridden on
28# the command line to support the older (less secure) PKCS1.5
29sign_rsa_pss = True
30
31AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
32
33class RSAPublicKey(univ.Sequence):
34 componentType = namedtype.NamedTypes(
35 namedtype.NamedType('modulus', univ.Integer()),
36 namedtype.NamedType('publicExponent', univ.Integer()))
37
38class RSA2048():
39 def __init__(self, key):
40 """Construct an RSA2048 key with the given key data"""
41 self.key = key
42
43 @staticmethod
44 def generate():
45 return RSA2048(RSA.generate(2048))
46
47 def export_private(self, path):
48 with open(path, 'wb') as f:
49 f.write(self.key.exportKey('PEM'))
50
51 def get_public_bytes(self):
52 node = RSAPublicKey()
53 node['modulus'] = self.key.n
54 node['publicExponent'] = self.key.e
55 return bytearray(encode(node))
56
57 def emit_c(self):
58 print(AUTOGEN_MESSAGE)
59 print("const unsigned char rsa_pub_key[] = {", end='')
60 encoded = self.get_public_bytes()
61 for count, b in enumerate(encoded):
62 if count % 8 == 0:
63 print("\n\t", end='')
64 else:
65 print(" ", end='')
66 print("0x{:02x},".format(b), end='')
67 print("\n};")
68 print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
69
Tamas Banf70ef8c2017-12-19 15:35:09 +000070 def sig_type(self):
71 """Return the type of this signature (as a string)"""
72 if sign_rsa_pss:
73 return "PKCS1_PSS_RSA2048_SHA256"
74 else:
75 return "PKCS15_RSA2048_SHA256"
76
77 def sig_len(self):
78 return 256
79
80 def sig_tlv(self):
81 return "RSA2048"
82
83 def sign(self, payload):
Tamas Ban581034a2017-12-19 19:54:37 +000084 converted_payload = bytes(payload)
85 sha = SHA256.new(converted_payload)
Tamas Banf70ef8c2017-12-19 15:35:09 +000086 if sign_rsa_pss:
87 signer = PKCS1_PSS.new(self.key)
88 else:
89 signer = PKCS1_v1_5.new(self.key)
90 signature = signer.sign(sha)
91 assert len(signature) == self.sig_len()
92 return signature
93
Tamas Banf70ef8c2017-12-19 15:35:09 +000094def load(path):
95 with open(path, 'rb') as f:
96 pem = f.read()
97 try:
98 key = RSA.importKey(pem)
99 if key.n.bit_length() != 2048:
100 raise Exception("Unsupported RSA bit length, only 2048 supported")
101 return RSA2048(key)
102 except ValueError:
Tamas Ban581034a2017-12-19 19:54:37 +0000103 raise Exception("Unsupported RSA key file")