blob: 9c5786d82e28f3b51b362571351fe4c193549f76 [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
10import sys
Valerio Setti862d14e2024-04-15 17:58:43 +020011from typing import Iterator
Valerio Setti7031a4e2024-04-16 10:31:15 +020012import re
Valerio Setti6bda5f52024-04-09 12:28:39 +020013# pylint: disable=wrong-import-position
14SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) + "/"
15sys.path.append(SCRIPT_DIR + "../../scripts/")
16from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
Valerio Setti8f404602024-04-15 15:09:10 +020017import scripts_path # pylint: disable=unused-import
Valerio Setti7126ba52024-03-29 16:59:40 +010018
Valerio Setti6bda5f52024-04-09 12:28:39 +020019OUTPUT_HEADER_FILE = SCRIPT_DIR + "../src/test_keys.h"
Valerio Setti862d14e2024-04-15 17:58:43 +020020BYTES_PER_LINE = 16
Valerio Setti7126ba52024-03-29 16:59:40 +010021
Valerio Setti862d14e2024-04-15 17:58:43 +020022def c_byte_array_literal_content(array_name: str, key_data: bytes) -> Iterator[str]:
23 yield 'const unsigned char '
24 yield array_name
25 yield '[] = {'
26 for index in range(0, len(key_data), BYTES_PER_LINE):
27 yield '\n '
28 for b in key_data[index:index + BYTES_PER_LINE]:
29 yield ' {:#04x},'.format(b)
30 yield '\n};'
31
Valerio Setti7031a4e2024-04-16 10:31:15 +020032def convert_der_to_c(array_name: str, key_data: bytes) -> str:
Valerio Setti862d14e2024-04-15 17:58:43 +020033 return ''.join(c_byte_array_literal_content(array_name, key_data))
Valerio Setti7126ba52024-03-29 16:59:40 +010034
Valerio Setti7031a4e2024-04-16 10:31:15 +020035def get_key_type(key: str) -> str:
36 if re.match('PSA_KEY_TYPE_RSA_.*', key):
37 return "rsa"
38 elif re.match('PSA_KEY_TYPE_ECC_.*', key):
39 return "ec"
40 else:
41 print("Unhandled key type {}".format(key))
42 return "unknown"
43
44def get_ec_key_family(key: str) -> str:
45 match = re.search(r'.*\((.*)\)', key)
46 if match is None:
47 raise Exception("Unable to get EC family from {}".format(key))
48 return match.group(1)
49
Valerio Setti9aa4fa92024-04-16 10:54:23 +020050# Legacy EC group ID do not support all the key types that PSA does, so the
51# following dictionaries are used for:
52# - getting prefix/suffix for legacy curve names
53# - understand if the curve is supported in legacy symbols (MBEDTLS_ECP_DP_...)
54EC_NAME_CONVERSION = {
55 'PSA_ECC_FAMILY_SECP_K1': {
56 192: ['secp', 'k1'],
57 224: ['secp', 'k1'],
58 256: ['secp', 'k1']
59 },
60 'PSA_ECC_FAMILY_SECP_R1': {
61 192: ['secp', 'r1'],
62 224: ['secp', 'r1'],
63 256: ['secp', 'r1'],
64 384: ['secp', 'r1'],
65 521: ['secp', 'r1']
66 },
67 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': {
68 256: ['bp', 'r1'],
69 384: ['bp', 'r1'],
70 512: ['bp', 'r1']
71 },
72 'PSA_ECC_FAMILY_MONTGOMERY': {
73 255: ['curve', '19'],
74 448: ['curve', '']
75 }
76}
77
78def get_ec_curve_name(priv_key: str, bits: int) -> str:
79 ec_family = get_ec_key_family(priv_key)
80 try:
81 prefix = EC_NAME_CONVERSION[ec_family][bits][0]
82 suffix = EC_NAME_CONVERSION[ec_family][bits][1]
83 except: # pylint: disable=bare-except
84 return ""
85 return prefix + str(bits) + suffix
86
87def get_look_up_table_entry(key_type: str, curve_or_keybits: str,
88 priv_array_name: str, pub_array_name: str) -> Iterator[str]:
89 yield "\n {{ {}, ".format("1" if key_type == "ec" else "0")
90 yield "{},\n".format(curve_or_keybits)
91 yield " {0}, sizeof({0}),\n".format(priv_array_name)
92 yield " {0}, sizeof({0}) }},".format(pub_array_name)
Valerio Setti7031a4e2024-04-16 10:31:15 +020093
Valerio Setti862d14e2024-04-15 17:58:43 +020094def main() -> None:
Valerio Setti6bda5f52024-04-09 12:28:39 +020095 # Remove output file if already existing.
Valerio Setti7126ba52024-03-29 16:59:40 +010096 if os.path.exists(OUTPUT_HEADER_FILE):
97 os.remove(OUTPUT_HEADER_FILE)
Valerio Setti7126ba52024-03-29 16:59:40 +010098
99 output_file = open(OUTPUT_HEADER_FILE, 'at')
Valerio Setti3e22bf22024-04-03 13:42:20 +0200100 output_file.write(
101 "/*********************************************************************************\n" +
102 " * This file was automatically generated from tests/scripts/generate_test_keys.py.\n" +
103 " * Please do not edit it manually.\n" +
Valerio Setti6bda5f52024-04-09 12:28:39 +0200104 " *********************************************************************************/\n"
Valerio Setti3e22bf22024-04-03 13:42:20 +0200105 )
Valerio Setti7126ba52024-03-29 16:59:40 +0100106
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200107 look_up_table = ""
108
109 # Get a list of private keys only in order to get a single item for every
110 # (key type, key bits) pair. We know that ASYMMETRIC_KEY_DATA
111 # contains also the public counterpart.
112 priv_keys = [key for key in ASYMMETRIC_KEY_DATA if re.match(r'.*_KEY_PAIR', key)]
113
114 for priv_key in priv_keys:
115 key_type = get_key_type(priv_key)
Valerio Setti7031a4e2024-04-16 10:31:15 +0200116 # Ignore keys which are not EC or RSA
117 if key_type == "unknown":
118 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200119
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200120 pub_key = re.sub('_KEY_PAIR', '_PUBLIC_KEY', priv_key)
121
122 for bits in ASYMMETRIC_KEY_DATA[priv_key]:
123 if key_type == "ec":
124 curve = get_ec_curve_name(priv_key, bits)
125 # Ignore EC curves unsupported in legacy symbols
126 if curve == "":
127 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200128 # Create output array name
129 if key_type == "rsa":
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200130 array_name_base = "_".join(["test", key_type, str(bits)])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200131 else:
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200132 array_name_base = "_".join(["test", key_type, curve])
133 array_name_priv = array_name_base + "_priv"
134 array_name_pub = array_name_base + "_pub"
Valerio Setti7031a4e2024-04-16 10:31:15 +0200135 # Convert bytearray to C array
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200136 c_array_priv = convert_der_to_c(array_name_priv, ASYMMETRIC_KEY_DATA[priv_key][bits])
137 c_array_pub = convert_der_to_c(array_name_pub, ASYMMETRIC_KEY_DATA[pub_key][bits])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200138 # Write the C array to the output file
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200139 output_file.write(''.join(["\n", c_array_priv, "\n", c_array_pub, "\n"]))
140 # Update the lookup table
141 if key_type == "ec":
142 curve_or_keybits = "MBEDTLS_ECP_DP_" + curve.upper()
143 else:
144 curve_or_keybits = str(bits)
145 look_up_table = look_up_table + \
146 ''.join(get_look_up_table_entry(key_type, curve_or_keybits,
147 array_name_priv, array_name_pub))
148 # Write the lookup table: the struct containing pointers to all the arrays we created above.
149 output_file.write("""
150struct predefined_key_element {
151 int is_ec; // 1 for EC keys; 0 for RSA
152 int curve_or_keybits;
153 const unsigned char *priv_key;
154 size_t priv_key_len;
155 const unsigned char *pub_key;
156 size_t pub_key_len;
157};
158
159struct predefined_key_element predefined_keys[] = {""")
160 output_file.write("{}\n}};\n".format(look_up_table))
Valerio Setti7126ba52024-03-29 16:59:40 +0100161
162if __name__ == '__main__':
Valerio Setti862d14e2024-04-15 17:58:43 +0200163 main()