bytes=(bits+7)/8;
bit=(bits-1)%8;
- mask=0xff<<bit;
+ mask=0xff<<(bit+1);
buf=(unsigned char *)OPENSSL_malloc(bytes);
if (buf == NULL)
}
#endif
- if (top)
+ if (top != -1)
{
- if (bit == 0)
+ if (top)
{
- buf[0]=1;
- buf[1]|=0x80;
+ if (bit == 0)
+ {
+ buf[0]=1;
+ buf[1]|=0x80;
+ }
+ else
+ {
+ buf[0]|=(3<<(bit-1));
+ }
}
else
{
- buf[0]|=(3<<(bit-1));
- buf[0]&= ~(mask<<1);
+ buf[0]|=(1<<bit);
}
}
- else
- {
- buf[0]|=(1<<bit);
- buf[0]&= ~(mask<<1);
- }
- if (bottom) /* set bottom bits to whatever odd is */
+ buf[0] &= ~mask;
+ if (bottom) /* set bottom bit if requested */
buf[bytes-1]|=1;
if (!BN_bin2bn(buf,bytes,rnd)) goto err;
ret=1;
}
#endif
-/* random number r: min <= r < min+range */
-int BN_rand_range(BIGNUM *r, BIGNUM *min, BIGNUM *range)
+
+/* random number r: 0 <= r < range */
+int BN_rand_range(BIGNUM *r, BIGNUM *range)
{
int n;
{
do
{
- /* range = 11..._2, so each iteration succeeds with probability > .75 */
- if (!BN_rand(r, n, 0, 0)) return 0;
+ /* 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);
}
* so 3*range (= 11..._2) is exactly one bit longer than range */
do
{
- if (!BN_rand(r, n + 1, 0, 0)) return 0;
+ if (!BN_rand(r, n + 1, -1, 0)) return 0;
/* If r < 3*range, use r := r MOD range
* (which is either r, r - range, or r - 2*range).
* Otherwise, iterate once more.
* Since 3*range = 11..._2, each iteration succeeds with
- * probability > .75. */
+ * probability >= .75. */
if (BN_cmp(r ,range) >= 0)
{
if (!BN_sub(r, r, range)) return 0;
while (BN_cmp(r, range) >= 0);
}
- if (min != NULL)
- {
- if (!BN_add(r, r, min)) return 0;
- }
-
return 1;
}