lab10
#include <iostream>
#include <cmath>
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
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;
}
long long modInverse(long long e, long long phi) {
long long m0 = phi, t, q;
long long x0 = 0, x1 = 1;
if (phi == 1)
return 0;
while (e > 1) {
q = e / phi;
t = phi;
phi = e % phi;
e = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0)
x1 += m0;
return x1;
}
void generateKeys(long long &n, long long &e, long long &d) {
long long p = 61, q = 53;
n = p * q;
long long phi = (p - 1) * (q - 1);
e = 17;
d = modInverse(e, phi);
}
long long encrypt(long long message, long long e, long long n) {
return modExp(message, e, n);
}
long long decrypt(long long ciphertext, long long d, long long n) {
return modExp(ciphertext, d, n);
}
int main() {
long long n, e, d;
generateKeys(n, e, d);
cout << "Public Key (e, n): (" << e << ", " << n << ")" << endl;
cout << "Private Key (d, n): (" << d << ", " << n << ")" << endl;
long long message;
cout << "Enter a message (as a number less than " << n << "): ";
cin >> message;
long long ciphertext = encrypt(message, e, n);
cout << "Encrypted Message: " << ciphertext << endl;
long long userCiphertext, userD, userN;
cout << "\nEnter the encrypted message: ";
cin >> userCiphertext;
cout << "Enter the private key (d): ";
cin >> userD;
cout << "Enter the modulus (n): ";
cin >> userN;
long long decryptedMessage = decrypt(userCiphertext, userD, userN);
cout << "Decrypted Message: " << decryptedMessage << endl;
return 0;
}
Comments
Post a Comment