|
-
April 4th, 2009, 11:44 AM
#6
Re: calculatin inverse for e in rsa
 Originally Posted by security
hey ,
can someone pliz help me with the project m doin..
i want to implement rsa crypto system in c++
but m finding it difficult to calculate d since i dont know how to code the part where we find inverse of e..
pliz i urgently need sm1 help..
here is toy-RSA ... for 32-bit prime integers....but in C
Code:
#include<stdio.h>
#include<string.h>
struct keys
{
unsigned long int n;
unsigned long int de;
};
int lenp,lend;
int testprime(int no)
{
int i;
for(i=2;i<no;i++)
{
if((no % i) == 0)
{
return 0;
}
}
return 1;
}
int testgcd(int dividend,int divisor)
{
int rem=-1;
while(rem != 0)
{
rem=dividend % divisor;
dividend=divisor;
if(rem != 0)
divisor=rem;
}
return divisor;
}
unsigned long int expocal(unsigned long int c,unsigned long int d,unsigned long int n)
{
unsigned long int i=0,ans=1;
for(i=1;i<=d;i++)
{
ans=ans%n;
ans=ans*c;
}
ans=ans%n;
return ans;
}
unsigned long int findd(unsigned long int e,unsigned long int phi)
{
unsigned long int d=1,rem=-1,test;
while(rem!=0)
{
test=e*d;
test=test-1;
rem=test%phi;
if(rem==0)
return d;
d++;
}
return 0;
}
unsigned long int rsa_encryption(struct keys publickey,unsigned int long m)
{
return expocal(m,publickey.de,publickey.n);
}
unsigned long int rsa_decryption(struct keys privatekey,unsigned long int c)
{
return expocal(c,privatekey.de,privatekey.n);
}
void padding(char *p)
{
int i;
for(i=0;i<lenp;i++)
{
p++;
}
for(i=lenp;i<lend;i++)
{
*p=(int) NULL;
p++;
}
}
void rsa_algorithm(unsigned long int p,unsigned long int q,int pt)
{
struct keys publickey,privatekey;
unsigned long int n,phi,e,d,ct;
register int i=0;
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i<phi;i++)
{
if(testgcd(phi,i)==1)
{
printf("\t| %lu |\t",i);
}
}
printf("\n\nSelect a value of e from the above list\n");
scanf("%lu",&e);
while(testgcd(phi,e)!=1)
{
printf("uncompatible value of e. choose another value for e\n");
scanf("%lu",&e);
}
publickey.n=n;
publickey.de=e;
privatekey.n=n;
d=findd(e,phi);
printf("d=%lu\n",d);
privatekey.de=d;
ct=rsa_encryption(publickey,pt);
printf("ct=%d\n",ct);
pt=rsa_decryption(privatekey,ct);
printf("pt=%d\n",pt);
}
int main()
{
unsigned long int pr1,pr2,pt;
printf("Enter an integer(plain-text value)");
scanf("%lu",&pt);
printf("enter 2 prime numbers");
scanf("%lu,%lu",&pr1,&pr2);
while(testprime(pr1)==0)
{
printf("the number %lu is not prime\nenter a prime no",pr1);
scanf("%lu",&pr1);
}
while(testprime(pr2)==0)
{
printf("the number %lu is not prime\nenter a prime no",pr2);
scanf("%lu",&pr2);
}
rsa_algorithm(pr1,pr2,pt);
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|