diff --git a/tests/api/test_wolfmath.c b/tests/api/test_wolfmath.c index 4c86856dd4..fa91c2cc97 100644 --- a/tests/api/test_wolfmath.c +++ b/tests/api/test_wolfmath.c @@ -193,6 +193,14 @@ int test_wc_export_int(void) ExpectIntEQ(wc_export_int(&mp, buf, &len, 0, WC_TYPE_HEX_STR), 0); /* hex version of 1234 is 04D2 and should be 4 digits + 1 null */ ExpectIntEQ(len, 5); + mp_clear(&mp); + + /* test mp_int too large for export buf */ + len = sizeof(buf); + ExpectIntEQ(mp_init(&mp), MP_OKAY); + ExpectIntEQ(mp_set_bit(&mp, 257), 0); + ExpectIntEQ(wc_export_int(&mp, buf, &len, keySz, WC_TYPE_UNSIGNED_BIN), + WC_NO_ERR_TRACE(BUFFER_E)); mp_clear(&mp); #endif diff --git a/wolfcrypt/src/wolfmath.c b/wolfcrypt/src/wolfmath.c index 20258001b9..06fb8ed017 100644 --- a/wolfcrypt/src/wolfmath.c +++ b/wolfcrypt/src/wolfmath.c @@ -253,14 +253,18 @@ int wc_export_int(mp_int* mp, byte* buf, word32* len, word32 keySz, else { /* for WC_TYPE_UNSIGNED_BIN keySz is used to zero pad. * The key size is always returned as the size */ + int mpSz = 0; if (*len < keySz) { *len = keySz; return BUFFER_E; } *len = keySz; + mpSz = mp_unsigned_bin_size(mp); + if (mpSz < 0 || (word32)mpSz > keySz) { + return BUFFER_E; + } XMEMSET(buf, 0, *len); - err = mp_to_unsigned_bin(mp, buf + - (keySz - (word32)mp_unsigned_bin_size(mp))); + err = mp_to_unsigned_bin(mp, buf + (keySz - (word32)mpSz)); } return err;