/*#include <stdio.h>
#include<math.h>
int candp(int a,int b,int c)
{
int r=1;
b=b+1;
while(b!=1)
{
r=r*a;
r=r%c;
b--;
}
printf("%d\n",r);
return r;
}
int fun(int x,int y)//公钥e与t的互素判断
{
int t;
while(y)
{
t=x;
x=y;
y=t%y;
}
if(x==1)
return 0;//x与y互素时返回0
else
return 1;//x与y不互素时返回1
}
void main()
{
int p,q,e,d,m,n,t,c,r;
char s;
printf("please input the p,q: ");
scanf("%d%d",&p,&q);
n=p*q;
printf("the n is %3d\n",n);
t=(p-1)*(q-1);
printf("the t is %3d\n",t);
printf("please input the e: ");
scanf("%d",&e);
if(e<1||e>t||fun(e,t))
{
printf("e is error,please input again: ");
scanf("%d",&e);
}
d=1;
while(((e*d)%t)!=1)
d++;
printf("then caculate out that the d is %d\n",d);
printf("the cipher please input 1\n");
printf("the plain please input 2\n");
scanf("%d",&r);
switch(r)
{
case 1: printf("input the m: "); //输入要加密的明文数字
scanf("%d",&m);
c=candp(m,e,n);
printf("the cipher is %d\n",c);break;
case 2: printf("input the c: "); //输入要解密的密文数字
scanf("%d",&c);
m=candp(c,d,n);
printf("the cipher is %d\n",m);break;
}
}*/
#include<stdio.h>
int candp(int a,int b,int c)//数据处理函数,实现幂的取余运算
{
int r=1;
b=b+1;
while(b!=1)
{
r=r*a;
r=r%c;
b--;
}
printf("%d\n",r);
return r;
}
int fun(int x,int y)//公钥e与t的互素判断
{
int t;
while(y)
{
t=x;
x=y;
y=t%y;
}
if(x==1)
return 0;//x与y互素时返回0
else
return 1;//x与y不互素时返回1
}
void main()
{
int p,q,e,d,m,n,t,c,r;
printf("请输入两个素数p,q:");
scanf("%d%d",&p,&q);
n=p*q;
printf("计算得n为%3d\n",n);
t=(p-1)*(q-1);//求n的欧拉数
printf("计算得t为%3d\n",t);
printf("请输入公钥e:");
scanf("%d",&e);
if(e<1||e>t||fun(e,t))
{
printf("e不合要求,请重新输入:");//e<1或e>t或e与t不互素时,重新输入
scanf("%d",&e);
}
d=1;
while(((e*d)%t)!=1)
d++;//由公钥e求出私钥d
printf("经计算d为%d\n",d);
printf("加密请输入1\n");//加密或解密选择
printf("解密请输入2\n");
scanf("%d",&r);
switch(r)
{
case 1:printf("请输入明文m:");//输入要加密的明文数字
scanf("%d",&m);c=candp(m,e,n);
printf("密文为%d\n",c);break;
case 2:printf("请输入密文c:");//输入要解密的密文数字
scanf("%d",&c);
m=candp(c,d,n);
printf("明文为%d\n",m);break;
}
}
- 1
- 2
前往页