blob: f407f3beebb988c3a224919e7b22ce9e0ee5f917 [file] [log] [blame]
Jens Wiklanderbc420742015-05-05 14:59:15 +02001#!/usr/bin/env python
2#
3# Copyright (c) 2015, Linaro Limited
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are met:
8#
9# 1. Redistributions of source code must retain the above copyright notice,
10# this list of conditions and the following disclaimer.
11#
12# 2. Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation
14# and/or other materials provided with the distribution.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26# POSSIBILITY OF SUCH DAMAGE.
27#
28
29def get_args():
30 from argparse import ArgumentParser
31
32 parser = ArgumentParser()
33 parser.add_argument('--key', required=True, help='Name of key file')
34 parser.add_argument('--in', required=True, dest='inf', \
35 help='Name of in file')
36 parser.add_argument('--out', required=True, help='Name of out file')
37 return parser.parse_args()
38
39def main():
40 from Crypto.Signature import PKCS1_v1_5
41 from Crypto.Hash import SHA256
42 from Crypto.PublicKey import RSA
43 import struct
44
45 args = get_args()
46
47 f = open(args.key, 'rb')
48 key = RSA.importKey(f.read())
49 f.close()
50
51 f = open(args.inf, 'rb')
52 img = f.read()
53 f.close()
54
55 signer = PKCS1_v1_5.new(key)
56 h = SHA256.new()
57
58 digest_len = h.digest_size
59 sig_len = len(signer.sign(h))
60 img_size = len(img)
61
62 magic = 0x4f545348 # SHDR_MAGIC
63 img_type = 0 # SHDR_TA
64 algo = 0x70004830 # TEE_ALG_RSASSA_PKCS1_V1_5_SHA256
65 shdr = struct.pack('<IIIIHH', \
66 magic, img_type, img_size, algo, digest_len, sig_len)
67
68 h.update(shdr)
69 h.update(img)
70 sig = signer.sign(h)
71
72 f = open(args.out, 'wb')
73 f.write(shdr)
74 f.write(h.digest())
75 f.write(sig)
76 f.write(img)
77 f.close()
78
79if __name__ == "__main__":
80 main()