RSA 算法:
其中加密encode和解密decode中的效率可以提高的log(n)
但是这个算法只是原型,只能对数字加密,对字符串加密时要将转换成AScII码的东东进行拆分才可以。要按位加密。当q,p过大时,将有溢出。改进的可以自己写一个大数类。但没有时间了,暂时就做成这个样子吧。
#include<iostream>
#include<string>
#include<ctime>
#include"math.h"
usingnamespacestd;

boolisPrime(long);//thenumberisprimeandreturntrue,elsereturnfalse;
longgcd(longa,longb);//findanumberwhichthetwonumberaandbdivideexactly.
longpublicKey(longp,longq);//usingp,qtocalculatethepublickeye.
longprivateKey(longe,longQn);//usinge,Qntocalculatetheprivatekeyd.
longgenerKey(constlongp,constlongq,long*pubKey,long*priKey);//getthepublickeyandprivatekey.Andreturnn=p*q.
//char*encode(char*,longn,longpubKey);//encodetheText
//char*decode(char*,longn,longpriKey);//decodetheTextwhichhasbeenencoded.
longencode(long,longn,longpubKey);//encodetheText
longdecode(long,longn,longpriKey);//decodetheTextwhichhasbeenencoded.
intmain()

...{

longp,q;
longpubKey;
longpriKey;
boolpass=true;
while(pass)

...{
cout<<"inputtwoprimenumbers!andthetwonumbersarebiggerthantwo!!"<<endl;
cin>>p>>q;
//srand(time(0));
//q=rand();
//p=rand();
if(isPrime(p)&&isPrime(q))
pass=false;
}
cout<<"p="<<p<<"q="<<q<<endl;
longn=generKey(p,q,&pubKey,&priKey);
cout<<"n:"<<n<<endl;
cout<<"inputthenumberforencoding!"<<endl;
longnum;
cin>>num;
//cout<<decode(encode(txt,n,pubKey),n,priKey);
longenText=encode(num,n,pubKey);
cout<<"encodetheText:"<<enText<<endl;
cout<<"decodetheText:"<<decode(enText,n,priKey)<<endl;
return0;
}

boolisPrime(longa)

...{
if(a>2)

...{
intb=2,c=sqrt(a);
for(;b<c;b++)

...{
if(a%b==0)
returnfalse;
}
returntrue;
}
returnfalse;
}

longgcd(longa,longb)

...{
intx=a%b;
if(x==0)
returnb;
else
returngcd(b,x);
}

longpublicKey(constlongp,constlongq,constlongQn)

...{

srand(time(0));
longe=rand();
if(e>=Qn)
e=3;
while(gcd(e,Qn)!=1)

...{

e++;
if(e>=Qn)

...{
e=3;
}
}
cout<<"e:"<<e<<endl;
returne;
}

longprivateKey(constlonge,constlongQn)

...{
srand(time(0));
longd=rand();
if(d>=Qn)
d=3;
while(e*d%Qn!=1||e==d)

...{
d++;
if(d>=Qn)

...{
d=3;
}
}
cout<<"d:"<<d<<endl;
returnd;
}

longgenerKey(constlongp,constlongq,long*pubKey,long*priKey)

...{
longn=p*q;
longQn=(p-1)*(q-1);
*pubKey=publicKey(p,q,Qn);
*priKey=privateKey(*pubKey,Qn);
returnn;
}




/**//*

char*encode(char*txt,longn,longpubKey)
{
intlength=strlen(txt);
char*text=newchar[length];
strcpy(text,txt);
for(inti=0;i<length;i++)
{

text[i]=(int)pow(text[i],pubKey)%n;
}
returntext;
}

char*decode(char*txt,longn,longpriKey)
{
intlength=strlen(txt);
char*text=newchar[length];
strcpy(text,txt);
for(inti=0;i<length;i++)
{
text[i]=(int)pow(text[i],priKey)%n;
}
returntext;
}
*/
longencode(longnum,longn,longpubKey)

...{
longtmp=1;
for(inti=0;i<pubKey;i++)

...{
tmp*=num;
tmp%=n;
}
returntmp;
}
longdecode(longnum,longn,longpriKey)

...{
longtmp=1;
for(inti=0;i<priKey;i++)

...{
tmp*=num;
tmp%=n;
}
returntmp;
}