This is RSA algorithm for public key cryptography in C language
1. Prime numbers are generated using C pseudo-random generator
2. Exponentiation is replaced with simple multiplication so even larger numbers can be calculated to mod within limits of integer [ 2Byte in Turbo C/C++ compiler i used)
-------------------------------------
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<time.h>
int d,e,n;
int GenPrime(int seed);
int GenCoPrime(int num);
int IsPrime(int num);
int findD(int m,int e);
int GenKeys();
int mod(int,int,int);
int main()
{ int i,j;
char plain[50];
int cipher[50];
int len;
time_t t;
srand((unsigned) time(&t));
clrscr();
GenKeys();
printf("\nEnter some text...\n");
gets(plain);
len=strlen(plain);
printf("\n Cipher.........\n");
for(i=0;i<len;i++)
{
cipher[i]=mod(plain[i],e,n);
printf("%c",cipher[i]);
}
printf("\n decrypted.........\n");
for(i=0;i<len;i++)
{
j=mod(cipher[i],d,n);
printf("%c",j);
}
getch();
return 0;
}
int mod(int base,int expo,int div)
{
long rem=1;
int i;
for(i=0;i<expo;i++)
{
rem=(rem*base)%div;
}
return (int)rem;
}
int GenKeys()
{
int p,q,m;
int tt1;
p=GenPrime(11);
q=GenPrime(10);
n=p*q;
printf("\n P=%d , Q=%d , n=%d",p,q,n);
m=(p-1)*(q-1);
printf("\n m=%d ",m);
e=GenCoPrime(m);
printf("\n e=%d ",e);
d=findD(m,e);
printf("\n d=%d ",d);
printf("\n Private key = {%d, %d} ",d,n);
printf("\n Public key = {%d, %d} ",e,n);
return 1;
}
int GenPrime(int seed)
{
int i,tmp;
for(i=seed;;i++)
{
if(IsPrime(tmp=i+1))
{
if(rand()%2)
return tmp;
}
if(IsPrime(tmp=i+3))
{
if(rand()%2)
return tmp;
}
if(IsPrime(tmp=i+7))
{
if(rand()%2)
return tmp;
}
if(IsPrime(tmp=i+9))
{
if(rand()%2)
return tmp;
}
}
}
int IsPrime(int num)
{ int i;
if(num==2 | num==3 | num ==5 | num==7 )
return 1;
else
{
for(i=2;i<num;i++)
{
if(num%i==0)
return 0;
}
if(i==num)
return 1;
else
return 0;
}
}
int GenCoPrime(int num)
{
int i;
for(i=2;i<num;i++)
{
if(num%i != 0)
return i;
}
return 0;
}
int findD(int m,int e)
{
int i;
int d,tmp;
for(i=0;i<32767;i++)
{
tmp=1+(i*m);
if(tmp%e==0)
return tmp/e;
}
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment