xref: /optee_os/scripts/pem_to_pub_c.py (revision 5118efbe82358fd69fda6e0158a30e59f59ba09d)
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    try:
25        from Cryptodome.PublicKey import RSA
26        from Cryptodome.Util.number import long_to_bytes
27    except ImportError:
28        from Crypto.PublicKey import RSA
29        from Crypto.Util.number import long_to_bytes
30
31    args = get_args()
32
33    with open(args.key, 'r') as f:
34        key = RSA.importKey(f.read())
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    with open(args.out, 'w') as f:
46        f.write("#include <stdint.h>\n")
47        f.write("#include <stddef.h>\n\n")
48        f.write("const uint32_t " + args.prefix + "_exponent = " +
49                str(key.publickey().e) + ";\n\n")
50        f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
51        i = 0
52        for x in array.array("B", long_to_bytes(key.publickey().n)):
53            f.write("0x" + '{0:02x}'.format(x) + ",")
54            i = i + 1
55            if i % 8 == 0:
56                f.write("\n")
57            else:
58                f.write(" ")
59        f.write("};\n")
60        f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" +
61                args.prefix + "_modulus);\n")
62
63
64if __name__ == "__main__":
65    main()
66