DEV Community

KateMLady
KateMLady

Posted on

Secure transfer

Usually it's hard to write a secure code without mechanisms (e.g. AES-256, Rijndael-256). But we can provide secure transfer of data, leaning on algorithm Diffie-Hellman.
Consept on Diffie-Hellman key exchange:

  1. 2 people wants to communicate using strong security. They have private key, like word ("fish") or letter ("D"). But need to turn it into public key
  2. In common space they decide to choose certain Mathematical (cryptographic) function: a^b mod n
  3. a meens "D", b and n choosing together, general for 2 people
  4. The last one: fuction result is sent to each other and decrypt by reverse Mathematical function.

Let's see the code!

void crypt(int p, int g, int x, string in, vector <pair<int, int> > &mas) {

            int y = power(g, x, p);

            cout << "Public key (p,g,y) = " << "(" << p << "," << g << "," << y << ")" << endl;
            cout << "Private key x = " << x << endl;

            cout << "\nChipter text:" << endl;

            for (unsigned int i = 0; i < size(in); i++) {
                int m = in[i] + 256;
                if (m > 0) {
                    cout << (char)m;

                    int k = rand() % (p - 2) + 1; // 1 < k < (p-1) 
                    int a = power(g, k, p);
                    int b = mul(power(y, k, p), m, p);
                    mas.push_back(make_pair(a, b));
                }
            }

            cout << endl;
        }
Enter fullscreen mode Exit fullscreen mode

You see p, g, y = a, b, n. And x - result of encrypted function (public key). m - internal value for counting each bits of message (m), which is encrypted with a private key.
crypt(593, 123, x, message_in, cypher); - example of call our function.

And being on the recipient's spot, we need to decrypt this message (m).

void decrypt(int p, int x, vector <pair<int, int> > mas, string &out) {

            cout << "\nDecrypted text:" << endl;

            unsigned int i = 0;
            while (i < mas.size()) {
                int a = 0;
                int b = 0;
                a = mas[i].first;
                b = mas[i].second;

                if (a != 0 && b != 0) {
                    cout << a << " " << b << endl;

                    int deM = mul(b, power(a, p - 1 - x, p), p);// m=b*(a^x)^(-1)mod p =b*a^(p-1-x)mod p
                    char m = static_cast<char>(deM);
                    out.push_back(m);

                    i++;
                }
            }

            cout << endl;
        }
Enter fullscreen mode Exit fullscreen mode

decrypt(593, x, cypher, messagge_out); - similarly for calling decrypt function. Here we already don't need all parametres - only private key.

Top comments (0)