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