RSA密钥设置算法:
- 随机选择两个大素数p,q,计算其乘积n,n就是加密和解密时的模。
- 计算n的欧拉函数值 Ω(n)。
- 选择与n互素的加密密钥e,e满足1 < e < Ω(n) 且 gcd(e,Ω(n)) =1。
- 公钥:{e,n}。
- 计算e关于Ω(n)的乘法逆元d。
- 私钥:{d,n}。
- 公布公钥,保留私钥。
代码实现(不现实,只是体现思想)
#include <iostream>
#include <math.h>
using namespace std;
struct RSAKey {
int key,mod;
RSAKey(int a,int b): key(a),mod(b) {}
void show() {
cout << "{" << key << "," << mod <<"}" <<endl;
}
};
int gcd(int a,int b) {
return b == 0? a : gcd(b,a%b);
}
bool isPrime(int a) {
if(a <= 1) return false;
for(int i=2;i<=sqrt(a);i++) {
if(a%i==0) return false;
}
return true;
}
int ErlerFun(int a,int b) {
return (a-1)*(b-1);
}
RSAKey Distribute_Public_Key(int a,int b,int& e) {
int N = ErlerFun(a,b);
for(e=2;e<=N;e++) {
if(gcd(e,a*b)==1 && gcd(e,N)==1) {
return RSAKey(e,a*b);
}
}
}
RSAKey Distribute_Private_Key(int a,int b,int e) {
int N = ErlerFun(a,b);
for(int i=2;;i++) {
if((e*i)%N==1) return RSAKey(i,a*b);
}
}
int main() {
cout << "请您先输入1个质数:" ;
int a,b;
cin >> a;
while(!isPrime(a)) {
cout << "您输入的不是质数,请再重新输入:";
cin >> a;
}
cout << "请您再输入1个质数:" ;
cin >> b;
while(!isPrime(b)) {
cout << "您输入的不是质数,请再重新输入:";
cin >> b;
}
if(a > b) swap(a,b);
cout << "正在计算:Loading..." <<endl;
int e = 0;
RSAKey Public_Key = Distribute_Public_Key(a,b,e);
RSAKey Private_Key = Distribute_Private_Key(a,b,e);
cout << "公布公钥:" ; Public_Key.show();
cout << "保留私钥:" ; Private_Key.show();
return 0;
}
进一步解释RSA: