#include "stdlib.h"
unsigned long n;
int e,d;
unsigned p,q;
unsigned char text_8[100];
unsigned text_16[100],secu_16[100];
void public_key_product();
void person_key_product();
int gcd(unsigned long,unsigned long);
unsigned power(unsigned,unsigned,unsigned long);
void convert_16_to_8(unsigned a[100]);
void convert_8_to_16();
void coder();
void decoder();
void get();
main()
{
while(getch()!='e')
{
clrscr();
printf("Please enter your text to coded:\n");
get();
public_key_product();
person_key_product();
coder();
printf("\nThe coded is:\n%s",text_8);
getch();
printf("\n(d=%d,n=%lu)",d,n);
decoder();
printf("\nThe code is\n%s",text_8);
}
}
void get()
{
printf("Enter the text('e' to exit):\n");
scanf("%s",text_8);
}
int gcd(unsigned long a,unsigned long b) /*The gcd(),you can get gcd((p-1),(q-1))*/
{
unsigned long c;
if(a>=b)
{
c=a%b;
if(c==0)
return 0;
else if (c==1)
return 1;
else gcd(b,c);
}
else gcd(b,a);
}
void public_key_product() /*The public_key*/
{
e=3;
p=2*random(50000)+1+30000;
while(!is_number(p)&&p<65536);
{
p+=2;
}
q=2*random(10000)+1+30000;
while(!is_number(q)&&q<65536);
{
q+=2;
}
n=(unsigned long )p*(unsigned long)q;
while(!gcd((unsigned long )(p-1)*(unsigned long )(q-1),e))
e++;
printf("(e=%d,n=%lu)",e,n);
}
void person_key_product() /*The person_key*/
{
int i=1;
while((((p-1)*(q-1)*i+1)%e)&&i>0)
i++;
d=((p-1)*(q-1)*i+1)/e;
}
int is_number(unsigned n) /*The is_numer,you can get n*/
{
unsigned m=1,b=0,a,j=n-1,i,z;
while(!j%2)
{
m*=2;
b++;
j/=2;
}
m=(n-1)/m;
a=random(n-1);
for(j=0;j<1000;j++)
{
a+=2;
if(a>2)
{
i=0;
z=power(a,m,n);
if((z!=1)&&(z!=(p-1)))
return 0;
while((i<b)&&(z!=(p-1)))
{
if((i>0)&&(z==1))
return 0;
z=power(z,2,p);
i+=1;
}
if(z!=(p-1))return 0;
}
return 1;
}
}
unsigned power(unsigned a,unsigned b,unsigned long c) /*The power,you can get a,b,c*/
{
unsigned long z=1,t;
for(t=a;b>0;b>>=1)
{
if(b%2==1)z=(z*t)%c;
t=(t*t)%c;
}
return z;
}
void convert_8_to_16()
{
int i;
for(i=0;i<100;i++)
text_16[i]=text_8[2*i]*256+text_8[2*i+1];
}
void convert_16_to_8(unsigned a[100])
{
int i=0,flag=0;
unsigned temp;
while(i<200&&flag<100)
{
temp=a[flag]/256;
text_8[i]=temp;
text_8[i+1]=a[flag]%256;
i+=2;
flag++;
}
}
void coder()
{
int i;
i=0;
convert_8_to_16();
while(text_16[i]!=0)
{
secu_16[i]=power(text_16[i],e,n);
i++;
}
convert_16_to_8(secu_16);
}
void decoder()
{
int i;
i=0;
while(secu_16[i]!=0)
{
text_16[i]=power(secu_16[i],d,n);
i++;
}
convert_16_to_8(text_16);
}
评论0