#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
unsigned long high_exp(unsigned long x,unsigned long y,unsigned long n)/*高次幂求摩*/
{
unsigned long e,f;
f=x%n;
while(y!=1)
{
e=x*f;
f=e%n;
y--;
}
return(f);
}
unsigned long pr_num()/*随机产生素数*/
{
unsigned long a,b,c;
srand((unsigned)time(NULL));
do
{
c=0;
a=rand()%50;
if(a==0)
continue;
for(unsigned long i=2; i<=(unsigned long)sqrt((double)a); i++)
{
b=a%i;
if(b==0) c+=1;
}
}while(c!=0||a==0);
return(a);
}
unsigned long gcd(unsigned long a,unsigned long d)/*欧几里德算法*/
{
int r;
do
{
r=a%d;
a=d;
d=r;
}while(r>0);
if(a=1) return 1;
else return 0;
}
unsigned long widen_gcd(unsigned long x,unsigned long y,unsigned long*a1,unsigned long *a2,unsigned long *b1,unsigned long *b2)
{
unsigned long q,r,a,b; /*扩展欧几里德算法*/
q=x/y;
r=x%y;
a=*a2-q*(*a1);
b=*b2-q*(*b2);
if(r==0)
{
return y;
}
*a2=*a1;
*b2=*b1;
*a1=a;
*b1=b;
return widen_gcd(y,r,a1,a2,b1,b2);
}
unsigned long prod_ek_dk(unsigned long *x,unsigned long *y)/*产生密钥*/
{
unsigned long e,d,p,q,n,t,b1,b2,a2;
e=0;a2=1;b1=1;b2=0;
srand((unsigned)time(NULL));
while(1)
{
p=pr_num();
q=pr_num();
if(p!=q)
break;
}
cout<<"p="<<p<<" "<<"q="<<q<<endl;
n=p*q;
t=(p-1)*(q-1);
while(1)
{
d=rand()%t;
if(gcd(d,t)&&d!=1) break;
}
cout<<"t="<<t<<endl;
widen_gcd(d,t,&e,&a2,&b1,&b2);
if(e<0)
{
e=e+t;
}
*x=e ;
*y=d ;
return(n);
}
unsigned long main()
{
unsigned long c,qq,d,n,e;
n=prod_ek_dk(&d,&e);
cout<<"d="<<d<<" "<<"e="<<e<<" "<<"n="<<n<<endl;
unsigned long ww=5;
c=high_exp(ww,d,n);
cout<<c<<endl;
qq=high_exp(c,e,n);
cout<<qq<<endl;
return 0;
}
有时候加解密可以成功,有时候不成功,
d的产生好象也有点问题,有时候产生的数和程序要求不符.
在C++里面怎么按字符 读取(输出到) TXT文件里面的数据