xref: /optee_os/scripts/pem_to_pub_c.py (revision b1d7375c01ec8bcbf3561d27425d320afed23bce)
1#!/usr/bin/env python
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('--prefix', required=True, \
12		help='Prefix for the public key exponent and modulus in c file')
13
14	parser.add_argument('--out', required=True, \
15		help='Name of c file for the public key')
16
17	parser.add_argument('--key', required=True, help='Name of key file')
18
19	return parser.parse_args()
20
21def main():
22	import array
23	from Crypto.PublicKey import RSA
24	from Crypto.Util.number import long_to_bytes
25
26	args = get_args();
27
28	f = open(args.key, 'r')
29	key = RSA.importKey(f.read())
30	f.close
31
32	f = open(args.out, 'w')
33
34	f.write("#include <stdint.h>\n");
35	f.write("#include <stddef.h>\n\n");
36
37	f.write("const uint32_t " + args.prefix + "_exponent = " +
38		str(key.publickey().e) + ";\n\n")
39
40	f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
41	i = 0;
42	for x in array.array("B", long_to_bytes(key.publickey().n)):
43		f.write("0x" + '{0:02x}'.format(x) + ",")
44		i = i + 1;
45		if i % 8 == 0:
46			f.write("\n");
47		else:
48			f.write(" ");
49	f.write("};\n");
50
51	f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" + \
52		args.prefix + "_modulus);\n")
53
54	f.close()
55
56if __name__ == "__main__":
57	main()
58