【文件属性】:
文件名称:RSA的c++代码
文件大小:3KB
文件格式:CPP
更新时间:2018-05-17 17:29:49
RSA 算法
#include
#include
using namespace std;
#define MAXLENGTH 500 //明文最大长度,即所允许最大整数个数
int size = 0;//保存要进行加密的正整数的个数
int p, q; //两个大素数
int n, phi; //n = p * q,phi = (p-1) * (q-1) 是n的欧拉函数值
int e; //{e, n}为公开密钥
int d; //{d, n}为秘密密钥
int clear[MAXLENGTH], Ciphertext[MAXLENGTH];//分别用于存放加//密前的明//文和加密后的密文
int DecryptionText[MAXLENGTH];//存放解密后的明文
////////////////////////////////////////////////////////////
//以下为加密算法
void Encryption()
{//加密算法
cout << " 请输入两个较大的素数:" ;
cin >> p >> q ;
cout << " p = " << p << ", q = " << q << endl;
n = p * q;//求解 n,
phi = (p - 1) * ( q - 1 );//求解 n 的欧拉函数值
cout << " n = " << n << ", phi = " << phi << endl;
cout << " 请从[0," << phi - 1 << "]中选择一个与 " << phi << " 互素的数 e:";
cin >> e;
float d0;
for( int i = 1; ; i++)
{///求解乘法逆元 e * d ≡ 1 (mod phi)
d0 = (float)(phi*i+1) / e;
if( d0 - (int)d0 == 0 )
break;
}
d = (int)d0;
cout << endl;
cout << " e = " << e << ", d = " << d << endl;
cout << " 公开密钥 Pk = {e,n} = {" << e << "," << n << "}" << endl;
cout << " 秘密密钥 Sk = {d,n} = {" << d << "," << n << "}" << endl;
cout << endl;
cout << " 请输入要加密的小于 " << n << "的 正整数并以以1 -1结束(如* * * 1 -1):" << endl;
cout << " 加密前的明文为:";
for( int i = 0; i < MAXLENGTH; i++)
Ciphertext[i] = 1;
int count;
for(int j = 0; j> clear[j];
if( clear[j] == -1 )
break;
count = e;
while(count > 0)
{ //对明文进行加密 Ciphertext =(clear)^ e mod n
Ciphertext[j] = (Ciphertext[j] * clear[j]) % n;
//加密算法
count-- ;
}
size=j; }
cout << " 密文为:" ;
int j = size;//实际密文长度
for(int k=0; k 0)
{//对密文进行解密 DecryptionText =(Ciphertext)^ d (mod n)
DecryptionText[j] = ((DecryptionText[j] * Ciphertext[j]) %n);
count-- ;
}
}
cout << " 解密后的明文为:";
for( int k = 0; k < size; k ++)
cout << DecryptionText[k] << " ";
cout << endl ;
cout << " 加密前的明文为:";