1#!/usr/bin/env python 2# SPDX-License-Identifier: BSD-2-Clause 3# 4# Copyright (c) 2015, Linaro Limited 5# All rights reserved. 6# 7# Redistribution and use in source and binary forms, with or without 8# modification, are permitted provided that the following conditions are met: 9# 10# 1. Redistributions of source code must retain the above copyright notice, 11# this list of conditions and the following disclaimer. 12# 13# 2. Redistributions in binary form must reproduce the above copyright notice, 14# this list of conditions and the following disclaimer in the documentation 15# and/or other materials provided with the distribution. 16# 17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 21# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27# POSSIBILITY OF SUCH DAMAGE. 28# 29 30def get_args(): 31 import argparse 32 33 parser = argparse.ArgumentParser() 34 parser.add_argument('--prefix', required=True, \ 35 help='Prefix for the public key exponent and modulus in c file') 36 37 parser.add_argument('--out', required=True, \ 38 help='Name of c file for the public key') 39 40 parser.add_argument('--key', required=True, help='Name of key file') 41 42 return parser.parse_args() 43 44def main(): 45 import array 46 from Crypto.PublicKey import RSA 47 from Crypto.Util.number import long_to_bytes 48 49 args = get_args(); 50 51 f = open(args.key, 'r') 52 key = RSA.importKey(f.read()) 53 f.close 54 55 f = open(args.out, 'w') 56 57 f.write("#include <stdint.h>\n"); 58 f.write("#include <stddef.h>\n\n"); 59 60 f.write("const uint32_t " + args.prefix + "_exponent = " + 61 str(key.publickey().e) + ";\n\n") 62 63 f.write("const uint8_t " + args.prefix + "_modulus[] = {\n") 64 i = 0; 65 for x in array.array("B", long_to_bytes(key.publickey().n)): 66 f.write("0x" + '{0:02x}'.format(x) + ",") 67 i = i + 1; 68 if i % 8 == 0: 69 f.write("\n"); 70 else: 71 f.write(" "); 72 f.write("};\n"); 73 74 f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" + \ 75 args.prefix + "_modulus);\n") 76 77 f.close() 78 79if __name__ == "__main__": 80 main() 81