The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Y
By Guest on 13th March 2023 08:00:08 AM | Syntax: TEXT | Views: 80



New paste | Download | Show/Hide line no. | Copy text to clipboard
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // Проверка на простое число
  7. bool is_prime(int num) {
  8.     if (num <= 1) {
  9.         return false;
  10.     }
  11.     for (int i = 2; i <= sqrt(num); i++) {
  12.         if (num % i == 0) {
  13.             return false;
  14.         }
  15.     }
  16.     return true;
  17. }
  18.  
  19. // Функция для нахождения НОД двух чисел
  20. int gcd(int a, int b) {
  21.     if (b == 0) {
  22.         return a;
  23.     }
  24.     return gcd(b, a % b);
  25. }
  26.  
  27. // Функция для нахождения d (закрытый ключ)
  28. int find_d(int e, int totient) {
  29.     int d = 0;
  30.     while ((d * e) % totient != 1) {
  31.         d++;
  32.     }
  33.     return d;
  34. }
  35.  
  36. int main() {
  37.     // Ввод простых чисел p и q
  38.     int p, q;
  39.     cout << "Enter two prime numbers: ";
  40.     cin >> p >> q;
  41.  
  42.     // Вычисление n и totient(n)
  43.     int n = p * q;
  44.     int totient = (p - 1) * (q - 1);
  45.  
  46.     // Ввод секретного ключа d
  47.     int d;
  48.     cout << "Enter the secret key d: ";
  49.     cin >> d;
  50.  
  51.     // Вывод открытого ключа e
  52.     int e = find_d(d, totient);
  53.     cout << "The public key is: " << e << endl;
  54.  
  55.     // Шифрование сообщения
  56.     string message;
  57.     cout << "Enter a message to encrypt: ";
  58.     cin.ignore();
  59.     getline(cin, message);
  60.  
  61.     int encrypted[message.length()];
  62.     for (int i = 0; i < message.length(); i++) {
  63.         encrypted[i] = pow(message[i], e) % n;
  64.     }
  65.  
  66.     // Расшифрование сообщения
  67.     string decrypted = "";
  68.     for (int i = 0; i < message.length(); i++) {
  69.         decrypted += pow(encrypted[i], d) % n;
  70.     }
  71.     cout << "The decrypted message is: " << decrypted << endl;
  72.  
  73.     return 0;
  74. }



  • Recent Pastes