lab11
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
long long modExp(long long base, long long exp, long long mod) {
long long result = 1;
while (exp > 0) {
if (exp % 2 == 1)
result = (result * base) % mod;
base = (base * base) % mod;
exp /= 2;
}
return result;
}
string xorEncryptDecrypt(const string &text, long long sharedKey) {
string result = text;
for (size_t i = 0; i < text.size(); i++) {
result[i] = text[i] ^ (sharedKey % 256);
}
return result;
}
int main() {
long long p, g, a, b;
cout << "Enter a large prime number (p): ";
cin >> p;
cout << "Enter a primitive root modulo p (g): ";
cin >> g;
cout << "Enter Alice's private key (a): ";
cin >> a;
cout << "Enter Bob's private key (b): ";
cin >> b;
long long A = modExp(g, a, p);
long long B = modExp(g, b, p);
cout << "Alice's Public Key (A): " << A << endl;
cout << "Bob's Public Key (B): " << B << endl;
long long shared_secret_Alice = modExp(B, a, p);
long long shared_secret_Bob = modExp(A, b, p);
if (shared_secret_Alice == shared_secret_Bob) {
cout << "Shared Secret Computed Successfully: " << shared_secret_Alice << endl;
} else {
cout << "Error: Shared secrets do not match!" << endl;
return 1;
}
cin.ignore();
string plainText;
cout << "Enter a plain text sentence or paragraph: ";
getline(cin, plainText);
string encryptedText = xorEncryptDecrypt(plainText, shared_secret_Alice);
cout << "Encrypted Message: " << encryptedText << endl;
string inputEncryptedText;
cout << "\nEnter the encrypted message: ";
getline(cin, inputEncryptedText);
string decryptedText = xorEncryptDecrypt(inputEncryptedText, shared_secret_Alice);
if (decryptedText == plainText) {
cout << "Decryption successful! Decrypted Message: " << decryptedText << endl;
} else {
cout << "Decryption failed! The decrypted message does not match the original plaintext." << endl;
}
return 0;
}
Comments
Post a Comment