From b599dc2b9d4659df53a28a52d7e9183bb8e3b980 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Thu, 28 Mar 2019 14:15:57 -0600 Subject: [PATCH] update wolfSSL_i2d_RSAPrivateKey function --- src/ssl.c | 29 ++++++++++++++++++++++------- tests/api.c | 6 ++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 57056978c..dbccd6975 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -29167,7 +29167,11 @@ WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **r, #if !defined(HAVE_FAST_RSA) /* Converts an internal RSA structure to DER format. -Returns size of DER on success and WOLFSSL_FAILURE if error */ + * If "pp" is null then buffer size only is returned. + * If "*pp" is null then a created buffer is set in *pp and the caller is + * responsible for free'ing it. + * Returns size of DER on success and WOLFSSL_FAILURE if error + */ int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp) { #if defined(WOLFSSL_KEY_GEN) @@ -29179,7 +29183,7 @@ int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp) WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey"); /* check for bad functions arguments */ - if ((rsa == NULL) || (pp == NULL)) { + if (rsa == NULL) { WOLFSSL_MSG("Bad Function Arguments"); return BAD_FUNC_ARG; } @@ -29210,12 +29214,23 @@ int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp) return ret; } - /* ret is the size of the DER buffer */ - for (i = 0; i < ret; i++) { - *(*pp + i) = *(der + i); + if (pp != NULL) { + if (*pp == NULL) { + /* create buffer and return it */ + *pp = (unsigned char*)XMALLOC(ret, NULL, DYNAMIC_TYPE_OPENSSL); + if (*pp == NULL) { + return WOLFSSL_FATAL_ERROR; + } + XMEMCPY(*pp, der, ret); + } + else { + /* ret is the size of the DER buffer */ + for (i = 0; i < ret; i++) { + *(*pp + i) = *(der + i); + } + *pp += ret; + } } - *pp += ret; - XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER); return ret; /* returns size of DER if successful */ #else diff --git a/tests/api.c b/tests/api.c index bf77d664f..9fe3b34a5 100644 --- a/tests/api.c +++ b/tests/api.c @@ -20744,8 +20744,14 @@ static void test_wolfSSL_d2i_PrivateKeys_bio(void) /*i2d RSAprivate key tests */ AssertIntEQ(wolfSSL_i2d_RSAPrivateKey(NULL, NULL), BAD_FUNC_ARG); + AssertIntEQ(wolfSSL_i2d_RSAPrivateKey(rsa, NULL), 1192); AssertIntEQ(wolfSSL_i2d_RSAPrivateKey(rsa, &bufPtr), sizeof_client_key_der_2048); + bufPtr = NULL; + AssertIntEQ(wolfSSL_i2d_RSAPrivateKey(rsa, &bufPtr), + sizeof_client_key_der_2048); + AssertNotNull(bufPtr); + free(bufPtr); #endif /* USE_CERT_BUFFERS_2048 WOLFSSL_KEY_GEN */ RSA_free(rsa); #endif /* NO_RSA */