Sunday 10 November 2013

RSA Algorithm code in C


!! RSA !! Public Key Cryptography
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int mrpt(int n)//miller robbin primility test
{
int s,t,x,i;
if(n > 2)
{
if(n%2==0)
return 0;
else
{
int temp=1;
s=0;
t=n-1;
while(t%2==0)
{
s=s+1;
t=t/2;
}
x=0;
while(x==0)
x=rand()%(n-1);
//printf("x==%d\n",x);
for(i=1;i < =t;i++)
{
//calculate x't mod n=temp
temp=(temp*x)%n;
}
//printf("x't mod n==%d\n",temp);
int i,stemp=1,pow=1;
for(i=1;i<=s;i++)
{
pow=pow*2;
}
for(i=1;i<=pow;i++)
{
stemp=(stemp*temp)%n;
}
if(stemp==1)
return 1;
else return 0;
}
}
else return 0; 
}
int gcd(int a,int b)//compute gcd of a,b
{
if(b==0)
 return a;
gcd(b,a%b);
}
int main()
{
   int i, num[2],p=5,q,phn,n,e,d;
   time_t t;
   //change base value and fix range of p and q
   int base=100;
   printf(" ______________\n|      RSA     |\n ----------
----\nGenerate prime Nums in range 1 to %d\n",base);
   //generate random numbers p and q   
   srand((unsigned) time(&t)); 
   for(i=0;i<2;i++)
   {
   while(1){
   num[i]=rand()%base;
   if(mrpt(num[i])&num[i]!=p)
   break;}
   p=num[i];
   }
   //choose p,q as large distinct prime number
   p=num[0];
   q=num[1];
   printf("\np is : %d\nq is : %d\n",p,q);
   //calculate phy(n)=p-1*q-1;
   phn=(p-1)*(q-1);
   printf("phy(n) : %d \n",phn);
   //calculate n=p*q;
   n=p*q;
   printf("n is : %d \n",n);
   //choose e such that 1<e<phn and gcd(e,phn)=1
   while(gcd(phn,e)!=1)
   e=rand()%phn;
   printf("e is : %d\n",e);
   //compute d such as multiplicative inverse of e.d=1mod phn
   for(i=1;(phn*i+1)%e!=0;i++);
   d=(phn*i+1)/e;
   printf("d is : %d\n",d);
   //publish (N,e) as public key
   //keep (p,q and d) secreatly
   printf("\nPublic key (N,e)    :( %d,%d )\n",n,e);
   printf("Secreat key (p,q,d) :( %d,%d,%d )\n",p,q,d);
   printf("Thanks !! End of program !!\n");
  return(0);
}

Compile By : gcc -o a rsa.c (In LINUX environment)
run : ./a
Special thanks : Sunil_Kumar
Thank you for sight !