I wrote the following C++ code for generating keys for RSA :
void keygen(long long int &e_key,long long int &d_key,long long int phival)
{
e_key = genrndnum(2,(phival));
while(gcd(e_key,phival)!=1)
{
e_key = genrndnum(2,(phival-1));
}
long long int k =0;
d_key = (1+(k*phival))/e_key;
while(((1+(k*phival))%e_key)!=0)
{
++k;
d_key = (1+(k*phival))/e_key;
}
return;
}
[Update]
Code for genrndnum().
long genrndnum(long lower_limit,long upper_limit)
{
srand(time(NULL));
long rdnum =0;
rdnum = lower_limit + (rand() % (int)(upper_limit - lower_limit + 1));
return rdnum;
}
[End Update]
[Update 2]
Keygen is a function to generate private and public keys.
Here e_key is Public key and d_key the private key. Both are passed by reference.
Then phival is the Euler totient function (ie., phi(x)). (This was calculated sometime earlier , not shown).
I got all these information from wikipedia.
[End Update 2]
[Update 3]
Code for finding gcd().
long long int gcd(long long int num1 , long long int num2)
{
if(num1 ==0 && num2==0)
{
return 0;
}
if(num1==0)
{
return num2;
}
if(num2 ==0)
{
return num1;
}
long long int remainder = 0;
do
{
remainder = num1%num2;
num1 = num2;
num2 = remainder;
}while(remainder!=0);
return num1;
}
Input Values for keygen().
The only input value for keygen() is :
phival = 43392.
[End Update 3]
[Update 4]
Output values : [Randomly generated]
p =337
q = 149
phi = 49728
Encryption key = 8893
k = 7
Private key = 39 (There is another problem here : Encryption and Private keys should be the same. No where in the code have i changed e_key during decryption.)
Public key = 39
Modulus = 50213
[End Update 4]
But i get the same value for Public key and private key. What is the mistake in the code ?