Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- long long ModularExponentiation(long long base, long long exponent, long long modulus) {
- long long result = 1;
- while (exponent > 0) {
- if (exponent % 2 == 1) {
- result = (result * base) % modulus;
- }
- base = (base * base) % modulus;
- exponent /= 2;
- }
- return result;
- }
- int EulerTotientFunction(int number) {
- int result = number;
- if (number % 2 == 0) {
- while (number % 2 == 0) {
- number /= 2;
- }
- result /= 2;
- }
- int i = 3;
- while (i * i <= number) {
- if (number % i == 0) {
- while (number % i == 0) {
- number /= i;
- }
- result /= i;
- result *= (i - 1);
- }
- i += 2;
- }
- if (number > 1) {
- result /= number;
- result *= (number - 1);
- }
- return result;
- }
- std::pair<int, int> GeneratePrivateKey() {
- int privateKey = 0, modulus;
- int publicKey;
- std::cout << "Enter the public key: ";
- std::cin >> publicKey >> modulus;
- for (int i = 1; i < modulus; ++i) {
- if ((i * publicKey) % EulerTotientFunction(modulus) == 1) {
- privateKey = i;
- std::cout << "Private key: " << privateKey << " " << modulus << std::endl;
- break;
- }
- }
- return { privateKey, modulus };
- }
- void DecodeMessage() {
- std::vector<int> encryptedCode;
- int number;
- std::cout << "Enter the encrypted numbers: ";
- while (std::cin >> number) {
- encryptedCode.push_back(number);
- if (std::cin.peek() == '\n')
- break;
- }
- auto [privateKey, modulus] = GeneratePrivateKey();
- std::string decryptedString;
- decryptedString += char(96 + ModularExponentiation(encryptedCode[0], privateKey, modulus));
- for (size_t i = 1; i < encryptedCode.size(); ++i) {
- int currentDecoded = ModularExponentiation(encryptedCode[i], privateKey, modulus);
- int difference = currentDecoded - encryptedCode[i - 1];
- if (difference < 0) difference += modulus;
- decryptedString += char(96 + difference);
- }
- std::cout << "Decrypted string: " << decryptedString << std::endl;
- }
- void EncodeMessage() {
- std::string message;
- std::cout << "Enter your message (no spaces): ";
- std::cin >> message;
- int publicKey, modulus;
- std::cout << "Enter the public key: ";
- std::cin >> publicKey >> modulus;
- int lastEncodedValue = ModularExponentiation(message[0] - 96, publicKey, modulus);
- std::string encryptedString = std::to_string(lastEncodedValue) + " ";
- for (size_t i = 1; i < message.length(); ++i) {
- lastEncodedValue = ModularExponentiation(message[i] - 96 + lastEncodedValue, publicKey, modulus);
- encryptedString += std::to_string(lastEncodedValue) + " ";
- }
- std::cout << "Encrypted string: " << encryptedString << std::endl;
- }
- int main() {
- std::cout << "1) Decode\n2) Encode\n";
- int choice;
- std::cin >> choice;
- if (choice == 1) {
- DecodeMessage();
- } else {
- EncodeMessage();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement