#include<iostream.h>
#include<stdio.h>
#include<math.h>
int pf_c(int m,int k);
int pf(int m1,int n1);
int gcd(int f);
int r;
int h;
void main()
{ int a,b,c,d,d1,a1,b1,c1;
cout<<"请输入你选择的2个大素数!"<<endl;
cin>>a1;
cin>>b1;
r=a1*b1;
c=(a1-1)*(b1-1);
c1=gcd(c);
cout<<"公开钥为:"<<c1<<endl;
cout<<"请选择你要的操作:1.加密 2.解密"<<endl;
cin>>a;
switch(a){
case 1: cout<<"请输入明文:"<<endl;
cin>>b;
cout<<"密文为:"<<pf_c(b,c1)<<endl;
break;
case 2: cout<<"请输入密文:"<<endl;
cin>>d;
d1=pf(c,c1);
cout<<"私密钥为:"<<d1<<endl;
cout<<"明文为:"<<pf_c(d,d1)<<endl;
break;
}
}
int pf_c(int m,int k)
{
int a,i1,a1,b[50],c1,c;
c=0;c1=1;i1=0;
do{
a=k/2;
a1=k%2;
b[i1]=a1;
k=a;
i1++;
}while(a>0);
i1--;
for(int i=i1;i>=0;i--)
{
c=2*c;
c1=(c1*c1)%r;
if(b[i]==1)
{
c=c+1;
c1=(c1*m)%r;
}
}
return c1;
}
int pf(int m1,int n1)
{
int x1=1,x2=0,x3;
int y1=0,y2=1,y3;
x3=m1;
y3=n1;
int d;
for(int i=0; ;i++)
{
int q=x3/y3;
int t1=x1-q*y1;
int t2=x2-q*y2;
int t3=x3-q*y3;
x1=y1;
x2=y2;
x3=y3;
y1=t1;
y2=t2;
y3=t3;
if(y3==1)
{
if(y2<0) d=m1+y2;
else d=y2;
break;
}
}
return d;
}
int gcd(int f)
{
int x1=1,x2=0,x3;
int y1=0,y2=1,y3;
for(int i1=2;i1<f;i1++)
{
x3=f;
y3=i1;
int q=x3/y3;
int t1=x1-q*y1;
int t2=x2-q*y2;
int t3=x3-q*y3;
x1=y1;
x2=y2;
x3=y3;
y1=t1;
y2=t2;
y3=t3;
if(y3==1)
{
return i1;
break;
}
}
}
ras 加密
最新推荐文章于 2023-12-22 09:07:57 发布