RSA 公钥加密算法C++模拟

RSA密钥设置算法:

  1. 随机选择两个大素数p,q,计算其乘积n,n就是加密和解密时的模
  2. 计算n的欧拉函数值 Ω(n)
  3. 选择与n互素的加密密钥e,e满足1 < e < Ω(n) 且 gcd(e,Ω(n)) =1
  4. 公钥:{e,n}
  5. 计算e关于Ω(n)的乘法逆元d
  6. 私钥:{d,n}
  7. 公布公钥,保留私钥。

代码实现(不现实,只是体现思想)

#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:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值