srand is causing my program to freeze

1k Views Asked by At

I have implemented the RSA algorithm in C++, the program is working however the srand calls are making the program slow. I have used srand for generating the two prime numbers and the encryption key (e). Here's the snippet

...............................................
do
{
    p = make_prime_number();
    q = make_prime_number();
}while(p == q);

phi = (p - 1) * (q - 1);
n = p * q;

do
{
    e = random_builder (20);

    int *t = extended_gcd (e, phi);
    d = t[0];
}while(gcd(e, phi) != 1 || d < 1 || d >= n );
...............................................

int random_builder(const int max)
{
    srand(time(NULL));

    return rand() % max + 1;
}

bool is_prime(const int num)
{
    for(int i = 2; i <= num/2; i++)
        if(num % i == 0) 
            return false;

    return true;
}

int make_prime_number()
{
    int num;

    do
    {
        num = random_builder(20);
    }while(not is_prime(num));

    return num;
}

Can we somehow speed up the process by modifying the seed in srand ?

2

There are 2 best solutions below

0
Greg Hewgill On BEST ANSWER

There is no need to call srand() more than once. Call it once at the start of your program, and then leave it alone.

After calling srand() with a specific seed value, the same sequence of random numbers is generated by rand(). Therefore, since you are calling with the current time in seconds, your random_builder() function only returns a different value once every second.

0
CodesInChaos On

You should not use rand() or srand at all. You should use a well seeded cryptographic PRNG. On linux you can simply read from /dev/urandom and on windows you can use CryptGenRandom.