xref: /optee_os/scripts/pem_to_pub_c.py (revision 0a6f2bcaec59ba016a066c08245244ebaa2aac81)
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    # Refuse public exponent with more than 32 bits. Otherwise the C
37    # compiler may simply truncate the value and proceed.
38    # This will lead to TAs seemingly having invalid signatures with a
39    # possible security issue for any e = k*2^32 + 1 (for any integer k).
40    if key.publickey().e > 0xffffffff:
41        raise ValueError(
42            'Unsupported large public exponent detected. ' +
43            'OP-TEE handles only public exponents up to 2^32 - 1.')
44
45    f = open(args.out, 'w')
46
47    f.write("#include <stdint.h>\n")
48    f.write("#include <stddef.h>\n\n")
49
50    f.write("const uint32_t " + args.prefix + "_exponent = " +
51            str(key.publickey().e) + ";\n\n")
52
53    f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
54    i = 0
55    for x in array.array("B", long_to_bytes(key.publickey().n)):
56        f.write("0x" + '{0:02x}'.format(x) + ",")
57        i = i + 1
58        if i % 8 == 0:
59            f.write("\n")
60        else:
61            f.write(" ")
62    f.write("};\n")
63
64    f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" +
65            args.prefix + "_modulus);\n")
66
67    f.close()
68
69
70if __name__ == "__main__":
71    main()
72