简单RSA,非大数,C++

#include <iostream>
using namespace std;
bool isPrime[1000];//True代表为素数
int x=1, y=0;//扩展欧几里得的解
void findPrime();
void exgcd(int a, int b);
int my_Pow(int x, int y, int mod);
int Prime[1000] = { 0 }, cnt = 0;//cnt为数组中素数个数
//RSA忘记的可以回忆下,推荐文章:http://www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html
int main()
{
    memset(isPrime, true, sizeof(isPrime));
    findPrime();//生成素数数组
    int p = Prime[5],q=Prime[7];//随机取两个素数
    int n = p * q;
    int fei_n = (p - 1) * (q - 1);
    cout << "p=" << p << endl << "q=" << q << endl << "n=" << n << endl << "fei_n=" << fei_n<<endl;
    int e=0;
    for (int t = 0; t < cnt; t++)
    {//求与fei_n互质且相对较小的一个数e,怕溢出
        if (fei_n % Prime[t] != 0)
        {
            e = Prime[t];
            cout << "e=" << e << endl;
            break;
        }
    }
    if(e!=0)
    exgcd(fei_n, e);//求逆元e^-1
    cout << "x="<<x<<endl<<"y="<<y<<endl;
    int d = y;//这里可能为负
    if (d < 0) d += fei_n;
    cout << "d=" << d << endl<<"验证(fei_n*x+e*y)%fei_n="<< (fei_n * x + e * y) % fei_n<<endl;
    int mingwen = 99;
    int miwen = my_Pow(mingwen, e, n);
    cout << "密文" << miwen<<endl;
    int jiemiwen = my_Pow(miwen, d, n);
    cout << "解密后的明文" << jiemiwen << endl;
    system("pause");
    return 0;
}

void findPrime()
{//素数筛
    for (int i = 2; i < 1000; i++)
    {
        if (isPrime[i])
        {
            Prime[cnt++] = i;
            for (int j = i + i; j < 1000; j += i)
            {
                isPrime[j] = false;
            }
        }
    }
}

void exgcd(int a, int b)//ax+by=gcd(a,b),默认a>b
{//看不懂的推荐个文章,https://www.cnblogs.com/hadilo/p/5914302.html
    if (b)
    {
        exgcd(b, a % b);
        int k = x;
        x = y;
        y = k - a / b * y;
    }
    else {
        x = 1;
        y = 0;
    }
}

int my_Pow(int x, int y,int mod)
{
    if (y == 0)
        return 1;
    int s = 1;
    while (y>0)
    {
        if (y & 0x01)//最低位,判断奇偶
        {
            s = s * x % mod;
            --y;
        }
        else
        {
            x = x * x%mod;
            y=y>>1;//除2
        }
    }
    return s;
}
posted @ 2020-11-02 21:37  ecnu_lxz  阅读(93)  评论(0编辑  收藏  举报