From 865ce8abcb61f3048afcfddec2ab3060e6a6f937 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Bodo=20M=C3=B6ller?= Date: Fri, 14 Dec 2001 10:09:01 +0000 Subject: [PATCH] fix BN_rand_range --- CHANGES | 6 ++++++ crypto/bn/bn_rand.c | 24 +++++++++++++----------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/CHANGES b/CHANGES index cc1e6cac48..18cb9e7b52 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,12 @@ Changes between 0.9.6b and 0.9.6c [XX xxx XXXX] + *) Fix BN_rand_range bug pointed out by Dominikus Scherkl + . (The previous implementation + worked incorrectly for those cases where range = 10..._2 and + 3*range is two bits longer than range.) + [Bodo Moeller] + *) Only add signing time to PKCS7 structures if it is not already present. [Steve Henson] diff --git a/crypto/bn/bn_rand.c b/crypto/bn/bn_rand.c index b368d12f80..4944ffbf23 100644 --- a/crypto/bn/bn_rand.c +++ b/crypto/bn/bn_rand.c @@ -238,22 +238,15 @@ static int bn_rand_range(int pseudo, BIGNUM *r, BIGNUM *range) n = BN_num_bits(range); /* n > 0 */ + /* BN_is_bit_set(range, n - 1) always holds */ + if (n == 1) { if (!BN_zero(r)) return 0; } - else if (BN_is_bit_set(range, n - 2)) - { - do - { - /* range = 11..._2, so each iteration succeeds with probability >= .75 */ - if (!bn_rand(r, n, -1, 0)) return 0; - } - while (BN_cmp(r, range) >= 0); - } - else + else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) { - /* range = 10..._2, + /* range = 100..._2, * so 3*range (= 11..._2) is exactly one bit longer than range */ do { @@ -272,6 +265,15 @@ static int bn_rand_range(int pseudo, BIGNUM *r, BIGNUM *range) } while (BN_cmp(r, range) >= 0); } + else + { + do + { + /* range = 11..._2 or range = 101..._2 */ + if (!bn_rand(r, n, -1, 0)) return 0; + } + while (BN_cmp(r, range) >= 0); + } return 1; } -- 2.25.1