#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class RSA
{
public:
RSA();
~RSA();
int primeNumber(int m);
void produce_key();
void encrypted_process();
void open_process();
int calculatemod(int num1,int num2);
void print();
private:
int p;
int q;
int xn;
int n;
int private_key;
int public_key;
int M_NUM;
int C_NUM;
int M_open;
};
RSA::RSA()
{
do
{
cout<<"请输入一个为素数的p值:"<<endl;
cin>>p;
}while(primeNumber(p)==0);
do
{
cout<<"请输入一个与P值不相等的素数q值:"<<endl;
cin>>q;
}while(primeNumber(q)==0||q==p);
n=p*q;
xn=(p-1)*(q-1);
private_key=0;
public_key=0;
M_NUM=0;
C_NUM=0;
M_open=0;
}
RSA::~RSA()
{
if(M_NUM==M_open)
cout<<"此加密算法和解密算法是正确的."<<endl;
else
cout<<"对不起,发生错误."<<endl;
}
void RSA::produce_key()
{
do
{
cout<<"产生的n和xn值分别为:"<<n<<" "<<xn<<endl;
cout<<"请输入一个公钥public_key,使其与xn互素且小于xn:"<<endl;
cin>>public_key;
}while(xn%public_key==0||primeNumber(public_key)==0||public_key>=xn);
cout<<"产生的公钥为:"<<public_key<<endl;
cout<<"私有密钥可以是下列的数字:"<<endl;
for(int i=1; ;i++)
{
if((i*xn+1)%public_key==0 && (i*xn+1)/public_key<xn)
{
private_key=(i*xn+1)/public_key;
break;
}
}
cout<<"产生的私钥为:"<<private_key<<endl;
}
void RSA::encrypted_process()
{
do
{
cout<<"请输入明文一个小于n的数M_NUM:"<<endl;
cin>>M_NUM;
}while(M_NUM>=n);
C_NUM=calculatemod(M_NUM,public_key);
}
void RSA::open_process()
{
M_open=calculatemod(C_NUM,private_key);
}
int RSA::calculatemod(int num1,int num2)
{
//解决fmod(pow(num1,num2),n)溢出问题,主要功能求余数
int t1,t2;
int mul=1;
t1=num2/5; //防止溢出
t2=num2%5;
for(int i=0;i<t1;i++) //防止溢出
{
mul*=fmod(pow(num1,5),n);
mul=fmod(mul,n); //防止在次溢出
}
mul*=fmod(pow(num1,t2),n);
mul=fmod(mul,n);
return mul;
}
int RSA::primeNumber(int m) //功能:验证是否为素数
{
int flag=1;
int temp=sqrt(m);
for(int i=2;i<=temp;i++)
{
if(m%i==0)
{
flag=0;
break;
}
}
if(flag==0) return 0;
else return 1;
}
void RSA::print()
{
cout<<"最终输出:"<<endl;
cout<<"你所输入的两个素数为:"<<p<<" "<<q<<endl;
cout<<"产生的n和xn值分别为:"<<n<<" "<<xn<<endl;
cout<<"产生的公有密钥为:"<<public_key<<endl;
cout<<"产生的私有密钥为:"<<private_key<<endl;
cout<<"未经加密的明文为:"<<M_NUM<<endl;
cout<<"经加密后的密文为:"<<C_NUM<<endl;
cout<<"经解密后的明文为:"<<M_open<<endl;
}
int main()
{
RSA rsa;
rsa.produce_key();
rsa.encrypted_process();
rsa.open_process();
rsa.print();
return 0;
}
不是很理想,不适合大整数的情况.