Home > Mobile >  I tried to implement the RSA encryption algorithm using cpp, but it takes too long and I don't
I tried to implement the RSA encryption algorithm using cpp, but it takes too long and I don't

Time:08-29

My code is here

//RSA.cpp
#include <iostream>
#include <cstring>
#include <ctime>
#include <random>
#include <vector>
#include <string>
#include "BigNum.hpp"
using namespace std;

BigNum mygcd(BigNum a, BigNum b)
{
    while(a != b)
    {
        if(a>b)
        {
            a = a - b;
        }
        else 
        {
            b = b - a;
        }
    }
    return a;
}
BigNum prime(int n)
{
    vector<BigNum> ans;
    ans.push_back(BigNum(2));
    ans.push_back(BigNum(3));
    for (int i = 0; i < n; i  )
    {
        BigNum addend = 1;
        for (auto j : ans)
        {
            addend = addend * j;
        }
        ans.push_back(addend   1);
    }
    return ans[ans.size() - 1];
}
BigNum exgcd(BigNum a, BigNum b, BigNum &x, BigNum &y)
{
    if (b == 0)
    {
        x = 1, y = 0;
        return a;
    }
    BigNum g = exgcd(b, a - (a / b) * b, x, y);
    BigNum t;
    t = x;
    x = y;
    y = t - a / b * y;
    return g;
}
BigNum niyuan(BigNum a, BigNum b)
{
    BigNum x, y;
    BigNum aa = exgcd(a, b, x, y);
    return (x   b) - ((x   b) / b) * b;
}
vector<BigNum> yinshu(BigNum n)
{
    vector<BigNum> ans;
    int a = 2;
    while (n / 2 > a)
    {
        if (n % a == 0)
        {
            ans.push_back(a);
        }
        a  ;
    }
    return ans;
}
vector<int> ToBit(BigNum obj){
    vector<int> r;
    while (obj != 0){
        r.push_back( (obj - (obj / 2) * 2 == 0) ? 0 : 1 );
        obj = obj / 2;
    }
    return r;
}
BigNum jiami(BigNum e, int i, BigNum n)
{
    BigNum addend = i;
    BigNum result = 1;
    vector<int>bitE = ToBit(e);
    int now = 0;
    while (now != bitE.size())
    { 
        if (bitE[now])
        {
            result = addend * result;
            result = result - (result / n) * n;
        }
        addend = addend * addend;
        now = now   1;
    }
    return result;
}
BigNum jiemi(BigNum d, BigNum i, BigNum n)
{
    BigNum addend = i;
    BigNum result = 1;
    vector<int>bitD = ToBit(d);
    int now = 0;
    while (now != bitD.size())
    {
        if (bitD[now])
        {
            result = addend * result;
            result = result - (result / n) * n;
        }
        addend = addend * addend;
        now = now   1;
    }
    return result;
}
int main()
{
    srand(time(0));
    BigNum p = prime(rand() % 20   1); 
    srand(time(0));
    BigNum q = prime(rand() % 20   1); 
    BigNum N = p * q;                  
    BigNum r = (p - 1) * (q - 1);      
sss:
    srand(time(0));
    BigNum e = random()   2;
    if (mygcd(e, r) - BigNum(1) > 0)
        goto sss;
    vector<BigNum> yinshus = yinshu(r);                        
    BigNum d = BigNum(niyuan(e, r));                             
    cout << "Alice send(" << N << ',' << e << ")to Bob" << endl; 
    cout << "Please input your massage:";                        
    string m;
    cin >> m; 
    vector<int> message;
    for (auto i : m)
    {
        message.push_back((int)i);
    }
    vector<BigNum> miwen;
    for (auto i : message)
    {
        miwen.push_back(jiami(e, i, N));
    }
    cout << "coded text:";
    for (auto i : miwen)
    {
        cout << i << " ";
    }
    vector<BigNum> minwen;
    for (auto i : miwen)
    {
        minwen.push_back(jiemi(d, i, N));
    }
    cout << "明文:";
    for (auto i : minwen)
    {
        cout << i << " ";
    }
    cout << endl;
}

I used a self-defined data structure called BigNum in order to store some large integers without them overflowing.

//BigNum.hpp
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;

#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4

class BigNum
{
private:
    int a[999]; 
    int len;    
public:
    BigNum()
    {
        len = 1;
        memset(a, 0, sizeof(a));
    }                                  
    BigNum(const int);                 
    BigNum(const char *);              
    BigNum(const BigNum &);            
    BigNum &operator=(const BigNum &); 

    friend istream &operator>>(istream &, BigNum &); 
    friend ostream &operator<<(ostream &, BigNum &); 

    BigNum operator (const BigNum &) const;
    BigNum operator-(const BigNum &) const; 
    BigNum operator*(const BigNum &) const; 
    BigNum operator/(const int &) const;    
    BigNum operator/(const BigNum &) const;

    BigNum operator^(const int &) const;   
    int operator%(const int &) const;      
    bool operator>(const BigNum &T) const; 
    bool operator>(const int &t) const;    

    bool operator<(const BigNum &) const;
    bool operator<=(const BigNum &) const;
    bool operator>=(const BigNum &) const;
    bool operator==(const BigNum &) const;
    bool operator!=(const BigNum &) const;

    void print(); 
};
BigNum::BigNum(const int b) 
{
    int c, d = b;
    len = 0;
    memset(a, 0, sizeof(a));
    while (d > MAXN)
    {
        c = d - (d / (MAXN   1)) * (MAXN   1);
        d = d / (MAXN   1);
        a[len  ] = c;
    }
    a[len  ] = d;
}
BigNum::BigNum(const char *s)
{
    int t, k, index, l, i;
    memset(a, 0, sizeof(a));
    l = strlen(s);
    len = l / DLEN;
    if (l % DLEN)
        len  ;
    index = 0;
    for (i = l - 1; i >= 0; i -= DLEN)
    {
        t = 0;
        k = i - DLEN   1;
        if (k < 0)
            k = 0;
        for (int j = k; j <= i; j  )
            t = t * 10   s[j] - '0';
        a[index  ] = t;
    }
}
BigNum::BigNum(const BigNum &T) : len(T.len) 
{
    int i;
    memset(a, 0, sizeof(a));
    for (i = 0; i < len; i  )
        a[i] = T.a[i];
}
BigNum &BigNum::operator=(const BigNum &n)
{
    int i;
    len = n.len;
    memset(a, 0, sizeof(a));
    for (i = 0; i < len; i  )
        a[i] = n.a[i];
    return *this;
}
istream &operator>>(istream &in, BigNum &b) 
{
    char ch[MAXSIZE * 4];
    int i = -1;
    in >> ch;
    int l = strlen(ch);
    int count = 0, sum = 0;
    for (i = l - 1; i >= 0;)
    {
        sum = 0;
        int t = 1;
        for (int j = 0; j < 4 && i >= 0; j  , i--, t *= 10)
        {
            sum  = (ch[i] - '0') * t;
        }
        b.a[count] = sum;
        count  ;
    }
    b.len = count  ;
    return in;
}
ostream &operator<<(ostream &out, BigNum &b) 
{
    int i;
    cout << b.a[b.len - 1];
    for (i = b.len - 2; i >= 0; i--)
    {
        cout.width(DLEN);
        cout.fill('0');
        cout << b.a[i];
    }
    return out;
}

BigNum BigNum::operator (const BigNum &T) const 
{
    BigNum t(*this);
    int i, big;
    big = T.len > len ? T.len : len;
    for (i = 0; i < big; i  )
    {
        t.a[i]  = T.a[i];
        if (t.a[i] > MAXN)
        {
            t.a[i   1]  ;
            t.a[i] -= MAXN   1;
        }
    }
    if (t.a[big] != 0)
        t.len = big   1;
    else
        t.len = big;
    return t;
}
BigNum BigNum::operator-(const BigNum &T) const 
{
    int i, j, big;
    bool flag;
    BigNum t1, t2;
    if (*this > T)
    {
        t1 = *this;
        t2 = T;
        flag = 0;
    }
    else
    {
        t1 = T;
        t2 = *this;
        flag = 1;
    }
    big = t1.len;
    for (i = 0; i < big; i  )
    {
        if (t1.a[i] < t2.a[i])
        {
            j = i   1;
            while (t1.a[j] == 0)
                j  ;
            t1.a[j--]--;
            while (j > i)
                t1.a[j--]  = MAXN;
            t1.a[i]  = MAXN   1 - t2.a[i];
        }
        else
            t1.a[i] -= t2.a[i];
    }
    t1.len = big;
    while (t1.a[t1.len - 1] == 0 && t1.len > 1)
    {
        t1.len--;
        big--;
    }
    if (flag)
        t1.a[big - 1] = 0 - t1.a[big - 1];
    return t1;
}

BigNum BigNum::operator*(const BigNum &T) const 
{
    BigNum ret;
    int i, j, up;
    int temp, temp1;
    for (i = 0; i < len; i  )
    {
        up = 0;
        for (j = 0; j < T.len; j  )
        {
            temp = a[i] * T.a[j]   ret.a[i   j]   up;
            if (temp > MAXN)
            {
                temp1 = temp - temp / (MAXN   1) * (MAXN   1);
                up = temp / (MAXN   1);
                ret.a[i   j] = temp1;
            }
            else
            {
                up = 0;
                ret.a[i   j] = temp;
            }
        }
        if (up != 0)
            ret.a[i   j] = up;
    }
    ret.len = i   j;
    while (ret.a[ret.len - 1] == 0 && ret.len > 1)
        ret.len--;
    return ret;
}
BigNum BigNum::operator/(const int &b) const 
{
    BigNum ret;
    int i, down = 0;
    for (i = len - 1; i >= 0; i--)
    {
        ret.a[i] = (a[i]   down * (MAXN   1)) / b;
        down = a[i]   down * (MAXN   1) - ret.a[i] * b;
    }
    ret.len = len;
    while (ret.a[ret.len - 1] == 0 && ret.len > 1)
        ret.len--;
    return ret;
}
int BigNum::operator%(const int &b) const 
{
    int i, d = 0;
    for (i = len - 1; i >= 0; i--)
    {
        d = ((d * (MAXN   1)) % b   a[i]) % b;
    }
    return d;
}
BigNum BigNum::operator^(const int &n) const 
{
    BigNum t, ret(1);
    int i;
    if (n < 0)
        exit(-1);
    if (n == 0)
        return 1;
    if (n == 1)
        return *this;
    int m = n;
    while (m > 1)
    {
        t = *this;
        for (i = 1; i << 1 <= m; i <<= 1)
        {
            t = t * t;
        }
        m -= i;
        ret = ret * t;
        if (m == 1)
            ret = ret * (*this);
    }
    return ret;
}
bool BigNum::operator>(const BigNum &T) const
{
    int ln;
    if (len > T.len)
        return true;
    else if (len == T.len)
    {
        ln = len - 1;
        while (a[ln] == T.a[ln] && ln >= 0)
            ln--;
        if (ln >= 0 && a[ln] > T.a[ln])
            return true;
        else
            return false;
    }
    else
        return false;
}
bool BigNum::operator>(const int &t) const 
{
    BigNum b(t);
    return *this > b;
}

void BigNum::print() 
{
    int i;
    cout << a[len - 1];
    for (i = len - 2; i >= 0; i--)
    {
        cout.width(DLEN);
        cout.fill('0');
        cout << a[i];
    }
    cout << endl;
}

bool BigNum::operator<(const BigNum &obj) const
{
    for (int i = 0; i < len; i  )
    {
        if (a[i] < obj.a[i])
            return true;
        if (a[i] > obj.a[i])
            return false;
    }
    return false;
}
bool BigNum::operator<=(const BigNum &obj) const
{
    for (int i = 0; i < len; i  )
    {
        if (a[i] < obj.a[i])
            return true;
        if (a[i] > obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator>=(const BigNum &obj) const
{
    for (int i = 0; i < len; i  )
    {
        if (a[i] > obj.a[i])
            return true;
        if (a[i] < obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator==(const BigNum &obj) const
{
    for (int i = 0; i < len; i  )
    {
        if (a[i] != obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator!=(const BigNum &obj) const
{
    for (int i = 0; i < len; i  )
    {
        if (a[i] != obj.a[i])
            return true;
    }
    return false;
}
BigNum BigNum::operator/(const BigNum &op2) const
{
    BigNum temp(*this);
    if (op2 == 0)
    {
        cout << "ERROR!!";
        for (int i = 0; i < len; i  )
            temp.a[i] = 0;
    }
    else if (*this < op2)
    {
        for (int i = 0; i < len; i  )
            temp.a[i] = 0;
    }
    else if (*this == op2)
    {
        temp.a[len - 1] = 1;
    }
    else if (op2 == 1)
    {
        temp = *this;
    }
    else if (op2 == 2)
    {

        int from = 0;
        for (int i = 0; i < len; i  )
        {
            if (temp.a[i] != 0)
            {
                from = i;
                break;
            }
        }

        int carry = 0;
        for (int i = from; i < len; i  )
        {
            if (temp.a[i] & 1)
            {
                if (carry == 1)
                    temp.a[i] = (temp.a[i]   10) / 2;
                else
                    temp.a[i] = temp.a[i] / 2;
                carry = 1;
            }
            else
            {
                if (carry == 1)
                    temp.a[i] = (temp.a[i]   10) / 2;
                else
                    temp.a[i] = temp.a[i] / 2;
                carry = 0;
            }
        }
    }
    else
    {
        BigNum begin(1), end("500000000000000000000000000000"); // 500000000000000000000000000000
        while (begin < end)
        {
            BigNum mid = (begin   end) / 2;
            BigNum res = mid * op2;

            if (res == 0 || res >= *this)
                end = mid;
            else
                begin = mid   1;
        }
        temp = begin;
        if (temp == 1)
            return 0;

        int tmp = len - 1;
        while (temp.a[tmp] == 0)
        {
            temp.a[tmp] = 9;
            tmp  ;
        }
        temp.a[tmp]--;
        return temp;
    }
    return temp;
}

When I run it, sometimes I get the error "malloc(): corrupted top size", sometimes it will run and then nothing happens, when I debug it, I find that the problem is in the "mygcd" function, the algorithm I use is too slow for a huge The algorithm I'm using is too slow for the huge number, but I don't know how to change it. I'm not sure where in the two files something is going wrong that I don't know about, and I can't guarantee that all the algorithms I'm using are correct and appropriate. Can anyone help me? Thanks a lot. My system is Ubuntu 22.04.1LTS gcc version 11.2.0 Now I deleted all the Chinese comments

CodePudding user response:

After applying all of the changes suggested in the comments:

  1. Remove using namespace std;
  2. Remove superfluous BigNum::operator= and BigNum::BigNum(BigNum&)
  3. Only implement fully BigNum::operator< and BigNum::operator==, and the other relational operators are based on those two operators
  4. Make BigNum::operator << have the second argument as a const reference to BigNum.

the compiler here warns of j not being initialized.

BigNum BigNum::operator*(const BigNum &T) const //两个大数之间的相乘运算
{
    BigNum ret;
    int i, j, up;
    //...
    ret.len = i   j;
    //...
}

You see the results of the run, with the Address Sanitizer showing that things are not working right.

When j is initialized to 0, then the program runs without error, at least the main you provided runs without error.


Edit:

On further inspection, you are accessing arr out-of-bounds. After changing the a to std::array<int, 999> a; and used at() within BigNum::operator *, a std::out_of_range exception is thrown:

Here is the updated code.

Also, please name your variables with meaningful names, not one letter names like a. Naming your variables properly will aid in understanding the code a lot better.

  • Related