@@ -25937,30 +25937,35 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
2593725937{
2593825938#ifndef WOLFSSL_ASN_TEMPLATE
2593925939 int ret = 0, i;
25940+ int mpSz;
2594025941 word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
2594125942 word32 sizes[RSA_INTS];
2594225943 byte seq[MAX_SEQ_SZ];
2594325944 byte ver[MAX_VERSION_SZ];
25945+ mp_int* keyInt;
25946+ #ifndef WOLFSSL_NO_MALLOC
25947+ word32 rawLen;
2594425948 byte* tmps[RSA_INTS];
25949+ #endif
2594525950
2594625951 if (key == NULL)
2594725952 return BAD_FUNC_ARG;
2594825953
2594925954 if (key->type != RSA_PRIVATE)
2595025955 return BAD_FUNC_ARG;
2595125956
25957+ #ifndef WOLFSSL_NO_MALLOC
2595225958 for (i = 0; i < RSA_INTS; i++)
2595325959 tmps[i] = NULL;
25960+ #endif
2595425961
2595525962 /* write all big ints from key to DER tmps */
2595625963 for (i = 0; i < RSA_INTS; i++) {
25957- mp_int* keyInt = GetRsaInt(key, i);
25958- int mpSz;
25959- word32 rawLen;
25960-
25964+ keyInt = GetRsaInt(key, i);
2596125965 ret = mp_unsigned_bin_size(keyInt);
2596225966 if (ret < 0)
25963- return ret;
25967+ break;
25968+ #ifndef WOLFSSL_NO_MALLOC
2596425969 rawLen = (word32)ret + 1;
2596525970 ret = 0;
2596625971 if (output != NULL) {
@@ -25971,8 +25976,11 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
2597125976 break;
2597225977 }
2597325978 }
25974-
2597525979 mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
25980+ #else
25981+ ret = 0;
25982+ mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, NULL);
25983+ #endif
2597625984 if (mpSz < 0) {
2597725985 ret = mpSz;
2597825986 break;
@@ -26004,15 +26012,33 @@ int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
2600426012 j += verSz;
2600526013
2600626014 for (i = 0; i < RSA_INTS; i++) {
26015+ /* copy from tmps if we have malloc, otherwise re-export with buffer */
26016+ #ifndef WOLFSSL_NO_MALLOC
2600726017 XMEMCPY(output + j, tmps[i], sizes[i]);
2600826018 j += sizes[i];
26019+ #else
26020+ keyInt = GetRsaInt(key, i);
26021+ ret = mp_unsigned_bin_size(keyInt);
26022+ if (ret < 0)
26023+ break;
26024+ ret = 0;
26025+ /* This won't overrun output due to the outLen check above */
26026+ mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, output + j);
26027+ if (mpSz < 0) {
26028+ ret = mpSz;
26029+ break;
26030+ }
26031+ j += mpSz;
26032+ #endif
2600926033 }
2601026034 }
2601126035
26036+ #ifndef WOLFSSL_NO_MALLOC
2601226037 for (i = 0; i < RSA_INTS; i++) {
2601326038 if (tmps[i])
2601426039 XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
2601526040 }
26041+ #endif
2601626042
2601726043 if (ret == 0)
2601826044 ret = (int)outLen;
0 commit comments