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 ?

What is the mistake in the code?You need to provide more information about what results you get against what you expect.

The program is somewhat large , while codeproject suggests not to dump the entire codebase. Will the forum allow me to insert such a large amount of code ? The program is organised into different files.

Please read my update. The problem i face is public and private keys are the same but asymmetric key cryptography rules it out.

phival = (193-1)*(227-1) = 43392.

Other values e_key and d_key are passed by reference for the sake of getting the keys.

clearly.`gcd()`

do?`e_key = 31213`

and`d_key = 23269`

.`rand()`

?