Good day to all

I implemented the RSA encryption algorithm, but it does not work for given p, q, n, e, d.

In order not to write a lot of code, I took two mutually simple p and q, calculated n, took e such that GCD (e, (p-1) * (q-1)) = 1, using the online calculator found the discovery key d which is equal to the inverse of modulo e.

Code:

#include <string> #include <iostream> static int p = 7; static int q = 29; static int n = p * q; static int e = 17; static int d = 89; bool encrypt(std::string& strToEncrypt) { if (strToEncrypt.size() < 1) { std::cerr << "Incorrect string to be encrypted.\n"; return false; } std::string buffStrToEncrypt = strToEncrypt; strToEncrypt.clear(); for (std::size_t i = 0; i < buffStrToEncrypt.size(); i++) { uint64_t k = pow(buffStrToEncrypt[i], e); int var = k % n; std::cout << var << " -- " << (char)var << std::endl; strToEncrypt += var; } return true; } bool decrypt(std::string& strToDecrypt) { if (strToDecrypt.size() < 1) { std::cerr << "Incorrect string to be encrypted.\n"; return false; } std::string buffStrToDecrypt = strToDecrypt; strToDecrypt.clear(); for (std::size_t i = 0; i < strToDecrypt.size(); i++) { uint64_t k = pow(buffStrToDecrypt[i], d); int var = k % n; std::cout << var << " -- " << (char)var << std::endl; strToDecrypt += var; } return true; } void main() { std::string str = "Hello"; std::cout << "Inputed: " << str << std::endl; encrypt(str); std::cout << "Encrypted: " << str << std::endl; decrypt(str); std::cout << "Decrypted: " << str << std::endl << std::endl; system("pause"); } 

But the algorithm does not work.

Here is what is displayed on the screen:

Inputed: Hello 99 -- c 99 -- c 99 -- c 99 -- c 99 -- c Encrypted: ccccc Decrypted:

Can someone tell me why it doesn't work?

    1 answer 1

    I'm not even trying to figure out all the code ... That's enough:

     uint64_t k = pow(buffStrToEncrypt[i], e); 

    Suppose the symbol is only Latin A - i.e. 65. e you equal 17. Total - 65^17 , which is approximately 6.6e30 . You try to stick it into a 64-bit integer ... With d=89 it is still much worse ...

    Not to mention the fact that encrypting text character by character is essentially to use a substitution cipher, which was famously coped with when the coolest computer was scores :)

    • I changed the data type to double, now everything is spoofed, but not decrypted - Yura Lisovskiy
    • one
      But you can not. Because the operation is purely integer. Now you get not overflow, but rounding :) - with the same zero success ... - Harry
    • And then what to do? - Yura Lisovskiy
    • one
      Use other methods. For example, long arithmetic. Or, for example, think that for a^n % m not necessary to read a^n - you can take 1 and multiply n times by a followed by taking the remainder from dividing by m ... - Harry