Fix for wc_export_int with WC_TYPE_HEX_STR, which was not returning the correct length.

This commit is contained in:
David Garske
2021-07-08 14:36:36 -07:00
parent 4f055653c7
commit e1b487ab9f
2 changed files with 45 additions and 22 deletions

View File

@ -42068,42 +42068,54 @@ static int test_get_digit (void)
/*
* Testing wc_export_int
*/
static int test_wc_export_int (void)
static int test_wc_export_int(void)
{
int ret = 0;
#if defined(WOLFSSL_PUBLIC_MP)
mp_int mp;
byte buf[256];
byte buf[32];
word32 keySz = (word32)sizeof(buf);
word32 len = (word32)sizeof(buf);
int encType = WC_TYPE_UNSIGNED_BIN;
printf(testingFmt, "wc_export_int()");
if (mp_init(&mp) != MP_OKAY) {
ret = -1;
}
if (ret == 0) {
ret = wc_export_int(NULL, buf, &len, keySz, encType);
ret = mp_set_int(&mp, 1234);
}
if (ret == 0) {
ret = wc_export_int(NULL, buf, &len, keySz, WC_TYPE_UNSIGNED_BIN);
if (ret == BAD_FUNC_ARG) {
ret = 0;
}
}
len = sizeof(buf)-1;
if (ret == 0) {
ret = wc_export_int(&mp, buf, &len, keySz, encType);
len = sizeof(buf)-1;
ret = wc_export_int(&mp, buf, &len, keySz, WC_TYPE_UNSIGNED_BIN);
if (ret == BUFFER_E) {
ret = 0;
}
}
len = sizeof(buf);
if (ret == 0) {
ret = wc_export_int(&mp, buf, &len, keySz, WC_TYPE_HEX_STR);
len = sizeof(buf);
ret = wc_export_int(&mp, buf, &len, keySz, WC_TYPE_UNSIGNED_BIN);
}
if (ret == 0) {
ret = wc_export_int(&mp, buf, &len, keySz, encType);
len = 4; /* test input too small */
ret = wc_export_int(&mp, buf, &len, 0, WC_TYPE_HEX_STR);
if (ret == BUFFER_E) {
ret = 0;
}
}
if (ret == 0) {
len = sizeof(buf);
ret = wc_export_int(&mp, buf, &len, 0, WC_TYPE_HEX_STR);
/* hex version of 1234 is 04D2 and should be 4 digits + 1 null */
if (ret == 0 && len != 5) {
ret = BAD_FUNC_ARG;
}
}
printf(resultFmt, ret == 0 ? passed : failed);

View File

@ -210,26 +210,37 @@ int wc_export_int(mp_int* mp, byte* buf, word32* len, word32 keySz,
{
int err;
if (mp == NULL)
if (mp == NULL || buf == NULL || len == NULL)
return BAD_FUNC_ARG;
/* check buffer size */
if (*len < keySz) {
*len = keySz;
return BUFFER_E;
}
*len = keySz;
XMEMSET(buf, 0, *len);
if (encType == WC_TYPE_HEX_STR) {
/* for WC_TYPE_HEX_STR the keySz is not used.
* The size is computed via mp_radix_size and checked with len input */
#ifdef WC_MP_TO_RADIX
err = mp_tohex(mp, (char*)buf);
int size = 0;
err = mp_radix_size(mp, MP_RADIX_HEX, &size);
if (err == MP_OKAY) {
/* make sure we can fit result */
if (*len < (word32)size) {
*len = (word32)size;
return BUFFER_E;
}
*len = (word32)size;
err = mp_tohex(mp, (char*)buf);
}
#else
err = NOT_COMPILED_IN;
#endif
}
else {
/* for WC_TYPE_UNSIGNED_BIN keySz is used to zero pad.
* The key size is always returned as the size */
if (*len < keySz) {
*len = keySz;
return BUFFER_E;
}
*len = keySz;
XMEMSET(buf, 0, *len);
err = mp_to_unsigned_bin(mp, buf + (keySz - mp_unsigned_bin_size(mp)));
}