Skip to content

Commit 0d18b25

Browse files
bigbrettdanielinux
authored andcommitted
fix keytools public key der export to use ml-dsa level passed as env var
1 parent 9454deb commit 0d18b25

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

tools/keytools/keygen.c

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,21 +1088,38 @@ static void keygen_ml_dsa(const char *priv_fname, uint32_t id_mask)
10881088

10891089
if (exportPubKey) {
10901090
if (saveAsDer) {
1091+
uint8_t* pubDer;
1092+
size_t pubDerSz;
1093+
int pubOutLen;
1094+
const int WITH_ALG_SPKI = 1;
1095+
1096+
/* Size the buffer based on the ML DSA level */
1097+
switch (ml_dsa_level) {
1098+
case WC_ML_DSA_44:
1099+
pubDerSz = ML_DSA_LEVEL2_PUB_KEY_DER_SIZE;
1100+
break;
1101+
case WC_ML_DSA_65:
1102+
pubDerSz = ML_DSA_LEVEL3_PUB_KEY_DER_SIZE;
1103+
break;
1104+
case WC_ML_DSA_87:
1105+
pubDerSz = ML_DSA_LEVEL5_PUB_KEY_DER_SIZE;
1106+
break;
1107+
default:
1108+
fprintf(stderr, "Error: Unsupported ML DSA level\n");
1109+
exit(1);
1110+
break;
1111+
}
1112+
pubDer = malloc(pubDerSz);
1113+
if (pubDer == NULL) {
1114+
fprintf(stderr,
1115+
"Error: Failed to allocate memory for DER export\n");
1116+
exit(1);
1117+
}
1118+
10911119
/* Export public key in DER format */
1092-
uint8_t pubDer[
1093-
#if ML_DSA_LEVEL == 2
1094-
ML_DSA_LEVEL2_PUB_KEY_DER_SIZE
1095-
#elif ML_DSA_LEVEL == 3
1096-
ML_DSA_LEVEL3_PUB_KEY_DER_SIZE
1097-
#elif ML_DSA_LEVEL == 5
1098-
ML_DSA_LEVEL5_PUB_KEY_DER_SIZE
1099-
#endif
1100-
];
1101-
int pubOutLen;
11021120

1103-
const int WITH_ALG_SPKI = 1;
1104-
pubOutLen = wc_Dilithium_PublicKeyToDer(
1105-
&key, pubDer, sizeof(pubDer), WITH_ALG_SPKI);
1121+
pubOutLen = wc_Dilithium_PublicKeyToDer(&key, pubDer, pubDerSz,
1122+
WITH_ALG_SPKI);
11061123
if (pubOutLen < 0) {
11071124
fprintf(stderr, "Unable to export public key to DER, ret=%d\n",
11081125
pubOutLen);
@@ -1113,6 +1130,8 @@ static void keygen_ml_dsa(const char *priv_fname, uint32_t id_mask)
11131130
fprintf(stderr, "Unable to export public key to file\n");
11141131
exit(1);
11151132
}
1133+
1134+
free(pubDer);
11161135
}
11171136
else {
11181137
/* Export public key in raw format */

0 commit comments

Comments
 (0)