From 22e9d4df59dc9b4792b5eb914b97092ddfae8096 Mon Sep 17 00:00:00 2001 From: tb <> Date: Mon, 5 Nov 2018 23:52:47 +0000 Subject: Introduce bn_rand_interval() that allows specifying an interval [a, b) from which a a BIGNUM is chosen uniformly at random. ok beck jsing --- src/lib/libcrypto/bn/bn_lcl.h | 3 ++- src/lib/libcrypto/bn/bn_rand.c | 29 ++++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) (limited to 'src/lib') diff --git a/src/lib/libcrypto/bn/bn_lcl.h b/src/lib/libcrypto/bn/bn_lcl.h index b8319dd700..d0f36822dc 100644 --- a/src/lib/libcrypto/bn/bn_lcl.h +++ b/src/lib/libcrypto/bn/bn_lcl.h @@ -1,4 +1,4 @@ -/* $OpenBSD: bn_lcl.h,v 1.29 2018/07/23 18:14:32 tb Exp $ */ +/* $OpenBSD: bn_lcl.h,v 1.30 2018/11/05 23:52:47 tb Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -583,6 +583,7 @@ BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int num); int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom); +int bn_rand_interval(BIGNUM *rnd, const BIGNUM *lower_inc, const BIGNUM *upper_exc); /* Explicitly const time / non-const time versions for internal use */ int BN_mod_exp_ct(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, diff --git a/src/lib/libcrypto/bn/bn_rand.c b/src/lib/libcrypto/bn/bn_rand.c index 8625757140..63b8af8b95 100644 --- a/src/lib/libcrypto/bn/bn_rand.c +++ b/src/lib/libcrypto/bn/bn_rand.c @@ -1,4 +1,4 @@ -/* $OpenBSD: bn_rand.c,v 1.20 2017/05/02 03:59:44 deraadt Exp $ */ +/* $OpenBSD: bn_rand.c,v 1.21 2018/11/05 23:52:47 tb Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -279,6 +279,33 @@ BN_rand_range(BIGNUM *r, const BIGNUM *range) return bn_rand_range(0, r, range); } +int +bn_rand_interval(BIGNUM *rnd, const BIGNUM *lower_inc, const BIGNUM *upper_exc) +{ + BIGNUM *len = NULL; + int ret = 0; + + if (BN_cmp(lower_inc, upper_exc) <= 0) + goto err; + + if ((len = BN_new()) == NULL) + goto err; + + if (!BN_sub(len, upper_exc, lower_inc)) + goto err; + + if (!bn_rand_range(0, rnd, len)) + goto err; + + if (!BN_add(rnd, rnd, lower_inc)) + goto err; + + ret = 1; + err: + BN_free(len); + return ret; +} + int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range) { -- cgit v1.2.3-55-g6feb