#include #include #include #include using namespace std; int MyPow(int base, int exp, int n) { int answer = base; int i; for(i = 2; i <= exp; i++) { answer = answer * base; answer = answer % n; } return answer; } int FindD(int e, int n) { int i; i = 1; while (i < n and (e*i) % n !=1) { ++i; } return i; } int main() { // select two distinct prime numbers int p {61}, q {53}; // compute n int n = p * q; // compute lambdaN, lcm(p-1, q-1) int lambdaN {lcm(p-1, q-1)}; // e is selected so it is coprime to lambdaN int e {17}; // d is the modular multiplicative inverse if e mod lambdaN int d {FindD(e, (p-1)*(q-1))}; int plainText, cipherText; vector code; cout << "p = " << p << endl; cout << "q = " << q << endl; cout << "n = " << n << endl; cout << "lambda N = " << lambdaN << endl; cout << endl; cout << "The public key is (" << n << ", " << e << ")" << endl; cout << "The private key is (" << n << ", " << d << ")" << endl; /* cout << "C(d,C(e, i)) " << endl; // c(m) = m^e % n // d(m) = m^d % n for(char i = 65; i < 91; ++i) { cipherText = MyPow(i, e, n); plainText = MyPow(cipherText, d, n); cout << char(i) << " " << cipherText << " " << char(plainText) << endl; } */ /* * cout << endl << endl; cout << "C(e,C(d, i)) " << endl; for(char i = 65; i < 91; ++i) { plainText = MyPow(i, d, n); cipherText = MyPow(plainText, e, n); cout << char(i) << " " << plainText << " " << char(cipherText) << endl; } */ cout << endl; cout << "Encoding Hello World, with public key" << endl; for(auto ch : "HELLO WORLD") { cipherText = MyPow(ch,e, n); code.push_back(cipherText); } code.pop_back(); for(auto num: code){ cout << num << " "; } cout << endl; cout << "Decoding with private key: " ; for(auto num: code) { cout << char(MyPow(num, d, n)); } cout << endl; code.clear(); cout << "Encoding Hello World, with private key" << endl; for(auto ch : "HELLO WORLD") { cipherText = MyPow(ch,d, n); code.push_back(cipherText); } code.pop_back(); for(auto num: code){ cout << num << " "; } cout << endl << endl; cout << "Decoding with public key: " ; for(auto num: code) { cout << char(MyPow(num, e, n)); } cout << endl; return 0; }