(主要是你的循环写的不对,输入的字符应该-'0'才能与正常的数字对应)
#include<stdio.h>
#include<math.h>
int
candp(int
a,int
b,int
c)
{int
r=1
int
s
int
i=1
for(i=1i<=bi++)r=r*a
printf("%d\
",r)
s=r%c
printf("%d\
",s)
return
s}
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
t=(p-1)*(q-1)
printf("the
n
is
%12d\
",n)
printf("please
input
the
e:")
scanf("%d",&e)
while(e<1||e>n)
//此处修改为while循环
{
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\
",d)
printf("the
cipher
please
input
1\
")
printf("the
plain
please
input
2\
")
scanf("%c",&s)
while((s-'0')!=1&&(s-'0')!=2)
//消除后面的getchar()
此处增加while循环注意括号内的字符
{scanf("%c",&s)}
switch(s-'0')
{
case
1:printf("intput
the
m:")
scanf("%d",&m)
c=candp(m,e,n)
printf("the
plain
is
%d\
",c)break
case
2:printf("input
the
c:")
scanf("%d",&c)
m=candp(c,d,n)
printf("the
cipher
is
%8d\
",m)
break
}
}
上学期交的作业,已通过老师在运行时间上的测试#include <stdio.h>
#include <stdlib.h>
unsigned long prime1,prime2,ee
unsigned long *kzojld(unsigned long p,unsigned long q) //扩展欧几里得算法求模逆
{
unsigned long i=0,a=1,b=0,c=0,d=1,temp,mid,ni[2]
mid=p
while(mid!=1)
{
while(p>q)
{p=p-q mid=pi++}
a=c*(-1)*i+ab=d*(-1)*i+b
temp=aa=cc=temp
temp=bb=dd=temp
temp=pp=qq=temp
i=0
}
ni[0]=cni[1]=d
return(ni)
}
unsigned long momi(unsigned long a,unsigned long b,unsigned long p) //模幂算法
{
unsigned long c
c=1
if(a>p) a=a%p
if(b>p) b=b%(p-1)
while(b!=0)
{
while(b%2==0)
{
b=b/2
a=(a*a)%p
}
b=b-1
c=(a*c)%p
}
return(c)
}
void RSAjiami() //RSA加密函数
{
unsigned long c1,c2
unsigned long m,n,c
n=prime1*prime2
system("cls")
printf("Please input the message:\n")
scanf("%lu",&m)getchar()
c=momi(m,ee,n)
printf("The cipher is:%lu",c)
return
}
void RSAjiemi() //RSA解密函数
{
unsigned long m1,m2,e,d,*ni
unsigned long c,n,m,o
o=(prime1-1)*(prime2-1)
n=prime1*prime2
system("cls")
printf("Please input the cipher:\n")
scanf("%lu",&c)getchar()
ni=kzojld(ee,o)
d=ni[0]
m=momi(c,d,n)
printf("The original message is:%lu",m)
return
}
void main()
{ unsigned long m
char cho
printf("Please input the two prime you want to use:\n")
printf("P=")scanf("%lu",&prime1)getchar()
printf("Q=")scanf("%lu",&prime2)getchar()
printf("E=")scanf("%lu",&ee)getchar()
if(prime1<prime2)
{m=prime1prime1=prime2prime2=m}
while(1)
{
system("cls")
printf("\t*******RSA密码系统*******\n")
printf("Please select what do you want to do:\n")
printf("1.Encrpt.\n")
printf("2.Decrpt.\n")
printf("3.Exit.\n")
printf("Your choice:")
scanf("%c",&cho)getchar()
switch(cho)
{ case '1':RSAjiami()break
case '2':RSAjiemi()break
case '3':exit(0)
default:printf("Error input.\n")break
}
getchar()
}
}