花了整个晚上,熬夜到快四点写的RSA加密算法。昨天熬夜到四点。今天写了一个下午。。不知道明天的四级会不会挂。同志们,需要的就拿去吧。适合信息安全数学基础。
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
int p,q,e;
int fn;
int m,c;
int flag = 0;
struct PU //公钥
{
int e;
int n;
} pu;
struct PR //密钥
{
int d;
int n;
} pr;
bool isprime(int m)//判断是素数的函数
{
if (m <= 1)
{
return false;
}
else
if(m == 2)
{
return true;
}
else
{
for(int i=2; i<=sqrt(m); i++)
{
if((m % i) == 0)
{
return false;
break;
}
}
return true;
}
}
void switch_to_bit(int b, int bin[32]) //转换成二进制的函数
{
int n = 0;
while( b > 0)
{
bin[n]=b%2;
n++;
b/=2;
}
}
void order(int &in1, int &in2)//排序函数,大数放在前面
{
int a = ( in1 > in2 ? in1 : in2);
int b = ( in1 < in2 ? in1 : in2);
in1 = a;
in2 = b;
}
int gcd(int a, int b) //求最大公约数的函数
{
order(a,b);
int r;
if(b == 0)
{
return a;
}
else
{
while(true)
{
r = a % b;
a = b;
b = r;
if (b == 0)
{
return a;
break;
}
}
}
}
int extend_euclid(int m, int bin) //用拓展欧几里得算法求乘法逆元素
{
order(m,bin);
int a[3],b[3],t[3];
a[0] = 1, a[1] = 0, a[2] = m;
b[0] = 0, b[1] = 1, b[2] = bin;
if (b[2] == 0)
{
return a[2] = gcd(m, bin);
}
if (b[2] ==1)
{
return b[2] = gcd(m, bin);
}
while(true)
{
if(b[2] ==1)
{
return b[1];
break;
}
int q = a[2] / b[2];
for(int i=0; i<3; i++)
{
t[i] = a[i] - q * b[i];
a[i] = b[i];
b[i] = t[i];
}
}
}
int modular_multiplication(int a, int b, int n)
{
int f = 1;
int bin[32];
switch_to_bit(b,bin);
for(int i=31; i>=0; i--)
{
f = (f * f) % n;
if(bin[i] == 1)
{
f = (f * a) % n;
}
}
return f;
}
void produce_key() //产生密钥的函数
{
cout<<"输入两个素数p和q:";
cin>>p>>q;
while (!(isprime(p)&&isprime(q)))
{
cout<<"输入错误!请重新输入"<<endl;
cout<<"输入两个素数p和q:";
cin>>p>>q;
}
pr.n = p * q;
pu.n = p * q;
fn = (p - 1) * (q - 1);
cout<<"fn = "<<fn<<endl;
cout<<"输入e的值 :";
cin>>e;
while((gcd(fn,e)!=1))
{
cout<<"e输入错误,请重新输入!";
cout<<"输入e的值 :";
cin>>e;
}
pr.d = (extend_euclid(fn,e) + fn) % fn;
pu.e = e;
flag = 1;
cout<<"PR.d: "<<pr.d<<" PR.n: "<<pr.n<<endl;
cout<<"PU.e: "<<pu.e<<" PU.n: "<<pu.n<<endl;
}
void encrypt() //加密的函数
{
if(flag == 0)
{
cout<<"设置密钥:"<<endl;
produce_key();
}
cout<<"输入m:";
cin>>m;
c = modular_multiplication(m,pu.e,pu.n);
cout<<"c的值为:"<<c<<endl;
}
void decrypt()
{
if(flag == 0)
{
cout<<"设置密钥:"<<endl;
produce_key();
}
cout<<"输入c:";
cin>>c;
m = modular_multiplication(c,pr.d,pr.n);
cout<<"解密之后,m是:"<<m<<endl;
}
void menu()
{
cout<<"请选择要进行的操作:"<<endl;
cout<<"1********加密********"<<endl;
cout<<"2********解密********"<<endl;
cout<<"0********退出********"<<endl;
}
int main()
{
int n;
menu();
while(1)
{
cout<<"请选择 "<<endl;
cin>>n;
switch(n)
{
case 0:exit(0);
case 1:encrypt();break;
case 2:decrypt();break;
default:break;
}
}
return 0;
}