Search code examples
c++encryptionrsasrand

srand is causing my program to freeze


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 ?


Solution

  • 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.