diff --git a/src/ssl.c b/src/ssl.c index d7ca32b17..3cbba9a10 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -52693,11 +52693,10 @@ int wolfSSL_mask_bits(WOLFSSL_BIGNUM* bn, int n) } #endif - /* WOLFSSL_SUCCESS on ok */ int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) { - int ret = 0; + int ret = WOLFSSL_FAILURE; int len; int initTmpRng = 0; WC_RNG* rng = NULL; @@ -52770,6 +52769,38 @@ int wolfSSL_BN_rand(WOLFSSL_BIGNUM* bn, int bits, int top, int bottom) return ret; } +/** + * N = length of range input var + * Generate N-bit length numbers until generated number is less than range + * @param r Output number + * @param range The upper limit of generated output + * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure + */ +int wolfSSL_BN_rand_range(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *range) +{ + int n; + WOLFSSL_MSG("wolfSSL_BN_rand_range"); + + if (r == NULL || range == NULL) { + WOLFSSL_MSG("Bad parameter"); + return WOLFSSL_FAILURE; + } + + n = wolfSSL_BN_num_bits(range); + + if (n <= 1) { + wolfSSL_BN_zero(r); + } + else { + do { + if (wolfSSL_BN_rand(r, n, 0, 0) == WOLFSSL_FAILURE) { + WOLFSSL_MSG("wolfSSL_BN_rand error"); + return WOLFSSL_FAILURE; + } + } while(wolfSSL_BN_cmp(r, range) >= 0); + } + return WOLFSSL_SUCCESS; +} /* WOLFSSL_SUCCESS on ok * code is same as wolfSSL_BN_rand except for how top and bottom is handled. diff --git a/tests/api.c b/tests/api.c index 359cb6882..f32dc09ba 100644 --- a/tests/api.c +++ b/tests/api.c @@ -36775,6 +36775,7 @@ static void test_wolfSSL_BN_rand(void) { #if defined(OPENSSL_EXTRA) BIGNUM* bn; + BIGNUM* range; printf(testingFmt, "wolfSSL_BN_rand()"); @@ -36790,6 +36791,13 @@ static void test_wolfSSL_BN_rand(void) AssertIntEQ(BN_rand(bn, 64, 0, 0), SSL_SUCCESS); BN_free(bn); + AssertNotNull(bn = BN_new()); + AssertNotNull(range = BN_new()); + AssertIntEQ(BN_rand(range, 64, 0, 0), SSL_SUCCESS); + AssertIntEQ(BN_rand_range(bn, range), SSL_SUCCESS); + BN_free(bn); + BN_free(range); + printf(resultFmt, passed); #endif } diff --git a/wolfssl/openssl/bn.h b/wolfssl/openssl/bn.h index ac8fd6634..fc6fda20c 100644 --- a/wolfssl/openssl/bn.h +++ b/wolfssl/openssl/bn.h @@ -104,6 +104,7 @@ WOLFSSL_API int wolfSSL_mask_bits(WOLFSSL_BIGNUM*, int n); WOLFSSL_API int wolfSSL_BN_pseudo_rand(WOLFSSL_BIGNUM*, int bits, int top, int bottom); +WOLFSSL_API int wolfSSL_BN_rand_range(WOLFSSL_BIGNUM *r, const WOLFSSL_BIGNUM *range); WOLFSSL_API int wolfSSL_BN_rand(WOLFSSL_BIGNUM*, int bits, int top, int bottom); WOLFSSL_API int wolfSSL_BN_is_bit_set(const WOLFSSL_BIGNUM*, int n); WOLFSSL_API int wolfSSL_BN_hex2bn(WOLFSSL_BIGNUM**, const char* str); @@ -187,6 +188,7 @@ typedef WOLFSSL_BN_GENCB BN_GENCB; #define BN_pseudo_rand wolfSSL_BN_pseudo_rand #define BN_rand wolfSSL_BN_rand +#define BN_rand_range wolfSSL_BN_rand_range #define BN_is_bit_set wolfSSL_BN_is_bit_set #define BN_hex2bn wolfSSL_BN_hex2bn