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