1#!/usr/bin/env python3 2# SPDX-License-Identifier: BSD-2-Clause 3# 4# Copyright (c) 2015, Linaro Limited 5 6 7def get_args(): 8 import argparse 9 10 parser = argparse.ArgumentParser() 11 parser.add_argument( 12 '--prefix', required=True, 13 help='Prefix for the public key exponent and modulus in c file') 14 parser.add_argument( 15 '--out', required=True, 16 help='Name of c file for the public key') 17 parser.add_argument('--key', required=True, help='Name of key file') 18 19 return parser.parse_args() 20 21 22def main(): 23 import array 24 from cryptography.hazmat.backends import default_backend 25 from cryptography.hazmat.primitives import serialization 26 from cryptography.hazmat.primitives.asymmetric import rsa 27 28 args = get_args() 29 30 with open(args.key, 'rb') as f: 31 data = f.read() 32 33 try: 34 key = serialization.load_pem_private_key(data, password=None, 35 backend=default_backend()) 36 key = key.public_key() 37 except ValueError: 38 key = serialization.load_pem_public_key(data, 39 backend=default_backend()) 40 41 # Refuse public exponent with more than 32 bits. Otherwise the C 42 # compiler may simply truncate the value and proceed. 43 # This will lead to TAs seemingly having invalid signatures with a 44 # possible security issue for any e = k*2^32 + 1 (for any integer k). 45 if key.public_numbers().e > 0xffffffff: 46 raise ValueError( 47 'Unsupported large public exponent detected. ' + 48 'OP-TEE handles only public exponents up to 2^32 - 1.') 49 50 with open(args.out, 'w') as f: 51 f.write("#include <stdint.h>\n") 52 f.write("#include <stddef.h>\n\n") 53 f.write("const uint32_t " + args.prefix + "_exponent = " + 54 str(key.public_numbers().e) + ";\n\n") 55 f.write("const uint8_t " + args.prefix + "_modulus[] = {\n") 56 i = 0 57 nbuf = key.public_numbers().n.to_bytes(key.key_size >> 3, 'big') 58 for x in array.array("B", nbuf): 59 f.write("0x" + '{0:02x}'.format(x) + ",") 60 i = i + 1 61 if i % 8 == 0: 62 f.write("\n") 63 else: 64 f.write(" ") 65 f.write("};\n") 66 f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" + 67 args.prefix + "_modulus);\n") 68 69 70if __name__ == "__main__": 71 main() 72