blob: 99209336922c7b7ff27762b7408793af5c1daf35 [file] [log] [blame]
Valerio Setti7126ba52024-03-29 16:59:40 +01001#!/usr/bin/env python3
2
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5
6"""Module generating EC and RSA keys to be used in test_suite_pk instead of
7generating the required key at run time. This helps speeding up testing."""
8
9import os
Valerio Setti862d14e2024-04-15 17:58:43 +020010from typing import Iterator
Valerio Setti7031a4e2024-04-16 10:31:15 +020011import re
Valerio Setti270dcd12024-04-08 13:44:41 +020012import argparse
Valerio Setti8f404602024-04-15 15:09:10 +020013import scripts_path # pylint: disable=unused-import
Valerio Settiee743392024-04-17 15:12:49 +020014from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
Valerio Setti7126ba52024-03-29 16:59:40 +010015
Valerio Settiee743392024-04-17 15:12:49 +020016OUTPUT_HEADER_FILE = os.path.dirname(os.path.abspath(__file__)) + "/../src/test_keys.h"
Valerio Setti862d14e2024-04-15 17:58:43 +020017BYTES_PER_LINE = 16
Valerio Setti7126ba52024-03-29 16:59:40 +010018
Valerio Setti862d14e2024-04-15 17:58:43 +020019def c_byte_array_literal_content(array_name: str, key_data: bytes) -> Iterator[str]:
20 yield 'const unsigned char '
21 yield array_name
22 yield '[] = {'
23 for index in range(0, len(key_data), BYTES_PER_LINE):
24 yield '\n '
25 for b in key_data[index:index + BYTES_PER_LINE]:
26 yield ' {:#04x},'.format(b)
27 yield '\n};'
28
Valerio Setti7031a4e2024-04-16 10:31:15 +020029def convert_der_to_c(array_name: str, key_data: bytes) -> str:
Valerio Setti862d14e2024-04-15 17:58:43 +020030 return ''.join(c_byte_array_literal_content(array_name, key_data))
Valerio Setti7126ba52024-03-29 16:59:40 +010031
Valerio Setti7031a4e2024-04-16 10:31:15 +020032def get_key_type(key: str) -> str:
33 if re.match('PSA_KEY_TYPE_RSA_.*', key):
34 return "rsa"
35 elif re.match('PSA_KEY_TYPE_ECC_.*', key):
36 return "ec"
37 else:
38 print("Unhandled key type {}".format(key))
39 return "unknown"
40
41def get_ec_key_family(key: str) -> str:
42 match = re.search(r'.*\((.*)\)', key)
43 if match is None:
44 raise Exception("Unable to get EC family from {}".format(key))
45 return match.group(1)
46
Valerio Setti9aa4fa92024-04-16 10:54:23 +020047# Legacy EC group ID do not support all the key types that PSA does, so the
48# following dictionaries are used for:
49# - getting prefix/suffix for legacy curve names
50# - understand if the curve is supported in legacy symbols (MBEDTLS_ECP_DP_...)
51EC_NAME_CONVERSION = {
52 'PSA_ECC_FAMILY_SECP_K1': {
Valerio Settiee743392024-04-17 15:12:49 +020053 192: ('secp', 'k1'),
54 224: ('secp', 'k1'),
55 256: ('secp', 'k1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020056 },
57 'PSA_ECC_FAMILY_SECP_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020058 192: ('secp', 'r1'),
59 224: ('secp', 'r1'),
60 256: ('secp', 'r1'),
61 384: ('secp', 'r1'),
62 521: ('secp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020063 },
64 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020065 256: ('bp', 'r1'),
66 384: ('bp', 'r1'),
67 512: ('bp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020068 },
69 'PSA_ECC_FAMILY_MONTGOMERY': {
Valerio Settiee743392024-04-17 15:12:49 +020070 255: ('curve', '19'),
71 448: ('curve', '')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020072 }
73}
74
75def get_ec_curve_name(priv_key: str, bits: int) -> str:
76 ec_family = get_ec_key_family(priv_key)
77 try:
78 prefix = EC_NAME_CONVERSION[ec_family][bits][0]
79 suffix = EC_NAME_CONVERSION[ec_family][bits][1]
Valerio Settiee743392024-04-17 15:12:49 +020080 except KeyError:
Valerio Setti9aa4fa92024-04-16 10:54:23 +020081 return ""
82 return prefix + str(bits) + suffix
83
Valerio Setti36188212024-04-17 16:12:12 +020084def get_look_up_table_entry(key_type: str, group_id_or_keybits: str,
Valerio Setti9aa4fa92024-04-16 10:54:23 +020085 priv_array_name: str, pub_array_name: str) -> Iterator[str]:
Valerio Setti36188212024-04-17 16:12:12 +020086 if key_type == "ec":
87 yield " {{ {}, 0,\n".format(group_id_or_keybits)
88 else:
89 yield " {{ 0, {},\n".format(group_id_or_keybits)
Valerio Setti9aa4fa92024-04-16 10:54:23 +020090 yield " {0}, sizeof({0}),\n".format(priv_array_name)
91 yield " {0}, sizeof({0}) }},".format(pub_array_name)
Valerio Setti7031a4e2024-04-16 10:31:15 +020092
Valerio Setti862d14e2024-04-15 17:58:43 +020093def main() -> None:
Valerio Setti270dcd12024-04-08 13:44:41 +020094 argparser = argparse.ArgumentParser()
95 argparser.add_argument("--output", required=True, help="Output file")
96 args = argparser.parse_args()
Valerio Setti7126ba52024-03-29 16:59:40 +010097
Valerio Setti270dcd12024-04-08 13:44:41 +020098 output_file = args.output
99 # Remove output file if already existing.
100 if os.path.exists(output_file):
101 print("Warning: {} already existing, it will be overwritten.", output_file)
102 os.remove(output_file)
103
104 output_file = open(output_file, 'at')
Valerio Setti3e22bf22024-04-03 13:42:20 +0200105 output_file.write(
106 "/*********************************************************************************\n" +
107 " * This file was automatically generated from tests/scripts/generate_test_keys.py.\n" +
108 " * Please do not edit it manually.\n" +
Valerio Setti6bda5f52024-04-09 12:28:39 +0200109 " *********************************************************************************/\n"
Valerio Setti3e22bf22024-04-03 13:42:20 +0200110 )
Valerio Setti7126ba52024-03-29 16:59:40 +0100111
Valerio Settiee743392024-04-17 15:12:49 +0200112 look_up_table = []
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200113
114 # Get a list of private keys only in order to get a single item for every
115 # (key type, key bits) pair. We know that ASYMMETRIC_KEY_DATA
116 # contains also the public counterpart.
Valerio Settiee743392024-04-17 15:12:49 +0200117 priv_keys = [key for key in ASYMMETRIC_KEY_DATA if '_KEY_PAIR' in key]
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200118
119 for priv_key in priv_keys:
120 key_type = get_key_type(priv_key)
Valerio Setti7031a4e2024-04-16 10:31:15 +0200121 # Ignore keys which are not EC or RSA
122 if key_type == "unknown":
123 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200124
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200125 pub_key = re.sub('_KEY_PAIR', '_PUBLIC_KEY', priv_key)
126
127 for bits in ASYMMETRIC_KEY_DATA[priv_key]:
128 if key_type == "ec":
129 curve = get_ec_curve_name(priv_key, bits)
130 # Ignore EC curves unsupported in legacy symbols
131 if curve == "":
132 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200133 # Create output array name
134 if key_type == "rsa":
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200135 array_name_base = "_".join(["test", key_type, str(bits)])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200136 else:
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200137 array_name_base = "_".join(["test", key_type, curve])
138 array_name_priv = array_name_base + "_priv"
139 array_name_pub = array_name_base + "_pub"
Valerio Setti7031a4e2024-04-16 10:31:15 +0200140 # Convert bytearray to C array
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200141 c_array_priv = convert_der_to_c(array_name_priv, ASYMMETRIC_KEY_DATA[priv_key][bits])
142 c_array_pub = convert_der_to_c(array_name_pub, ASYMMETRIC_KEY_DATA[pub_key][bits])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200143 # Write the C array to the output file
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200144 output_file.write(''.join(["\n", c_array_priv, "\n", c_array_pub, "\n"]))
145 # Update the lookup table
146 if key_type == "ec":
Valerio Setti36188212024-04-17 16:12:12 +0200147 group_id_or_keybits = "MBEDTLS_ECP_DP_" + curve.upper()
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200148 else:
Valerio Setti36188212024-04-17 16:12:12 +0200149 group_id_or_keybits = str(bits)
150 look_up_table.append(''.join(get_look_up_table_entry(key_type, group_id_or_keybits,
Valerio Settiee743392024-04-17 15:12:49 +0200151 array_name_priv, array_name_pub)))
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200152 # Write the lookup table: the struct containing pointers to all the arrays we created above.
153 output_file.write("""
154struct predefined_key_element {
Valerio Setti36188212024-04-17 16:12:12 +0200155 int group_id; // EC group ID; 0 for RSA keys
156 int keybits; // bits size of RSA key; 0 for EC keys
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200157 const unsigned char *priv_key;
158 size_t priv_key_len;
159 const unsigned char *pub_key;
160 size_t pub_key_len;
161};
162
Valerio Settiee743392024-04-17 15:12:49 +0200163struct predefined_key_element predefined_keys[] = {
164""")
165 output_file.write("\n".join(look_up_table))
166 output_file.write("\n};\n")
Valerio Setti7126ba52024-03-29 16:59:40 +0100167
168if __name__ == '__main__':
Valerio Setti862d14e2024-04-15 17:58:43 +0200169 main()