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