Botan  1.11.15
src/lib/math/bigint/big_rand.cpp
Go to the documentation of this file.
00001 /*
00002 * BigInt Random Generation
00003 * (C) 1999-2007 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/bigint.h>
00009 #include <botan/parsing.h>
00010 
00011 namespace Botan {
00012 
00013 /*
00014 * Randomize this number
00015 */
00016 void BigInt::randomize(RandomNumberGenerator& rng,
00017                        size_t bitsize)
00018    {
00019    set_sign(Positive);
00020 
00021    if(bitsize == 0)
00022       clear();
00023    else
00024       {
00025       secure_vector<byte> array = rng.random_vec((bitsize + 7) / 8);
00026 
00027       if(bitsize % 8)
00028          array[0] &= 0xFF >> (8 - (bitsize % 8));
00029       array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
00030       binary_decode(&array[0], array.size());
00031       }
00032    }
00033 
00034 /*
00035 * Generate a random integer within given range
00036 */
00037 BigInt BigInt::random_integer(RandomNumberGenerator& rng,
00038                               const BigInt& min, const BigInt& max)
00039    {
00040    BigInt range = max - min;
00041 
00042    if(range <= 0)
00043       throw Invalid_Argument("random_integer: invalid min/max values");
00044 
00045    return (min + (BigInt(rng, range.bits() + 2) % range));
00046    }
00047 
00048 }