Consider this method that works well:
public static bool mightBePrime(int N) {
BigInteger a = rGen.Next (1, N-1);
return modExp (a, N - 1, N) == 1;
}
Create byte array and convert to BigInteger:
public BigInteger random_generate(BigInteger maxValue)
{
Random random = new Random();
byte[] maxValue_array = maxValue.ToByteArray();
byte[] randomValue_array = new byte[maxValue_array.Count()];
bool on_limit = true; //make sure randomValue won't greater than maxValue
for (int generate_byte = maxValue_array.Count() - 1; generate_byte >= 0; generate_byte--)
{
byte random_byte = 0;
if (on_limit)
{
random_byte = (byte)random.Next(maxValue_array[generate_byte]);
if (random_byte != (byte)random.Next(maxValue_array[generate_byte]))
{
on_limit = false;
}
}
else
{
random_byte = (byte)random.Next(256);
}
randomValue_array[generate_byte] = random_byte;
}
return new BigInteger(randomValue_array);
}
If the maxValue is too small, than the random will generate the same value. So you can set the random outside the function:
static void Main(string[] args)
{
Random random = new Random();
BigInteger i = random_generate(10, random); //10 is just a example
}
public BigInteger random_generate(BigInteger maxValue, Random random)
{
byte[] maxValue_array = maxValue.ToByteArray();
//...rest of the code...
}