1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
|
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <math.h>
#include <exception>
#include <stdexcept>
using namespace std;
int p, q, n, e = 7, d, tot;
string text = "Hello";
//Checks if the number is prime or not
bool isPrime(int a)
{
for (int i = 2; i < a / 2; i++)
{
if (a % i == 0) return false;
}
return true;
}
void setkeys()
{
int num = 11;
srand(time(0));
p = rand() % num + 5;
while (!isPrime(p))
{
p = rand() % num + 5;
}
q = rand() % num + 5;
while (!isPrime(q) || q == p)
{
q = rand() % num + 5;
}
/*q = 11;
p = 17;*/
n = p * q;
tot = (p - 1) * (q - 1);
e = 7;
}
int LCD(int a, int b)
{
int total = 1;
if (b <= 0) return a;
else {
int q = a / b;
int r = a - q * b;
a = b;
b = r;
LCD(a, b);
}
}
int calcNegativeMod(int n1, int mod)
{
n1 = abs(n1);
int i = 1;
while (mod * i < n1) i++;
int ans = mod * i - n1;
return ans;
}
int findE()
{
int er = 2;
while (LCD(er, tot) != 1) er++;
return er;
}
int findIn(int n, int phi)
{
int r = 1;
for (int i = 1; i < phi; i++)
{
if ((i * n) % phi == 1)
{
r = i;
break;
}
}
cout << "d is " << r << endl;
return r;
}
string encrypt(string s)
{
e = findE();
cout << "Public key is " << e << endl;
string dec = "";
char c = '\0';
for (int i = 0; i < s.length(); i++)
{
int h = (int)s.at(i);
long long a = ((long long)pow(h, e));
a = a % n;
if (a < 0) a = calcNegativeMod(a, n);
c = a;
dec += c;
c = '\0';
}
return dec;
}
string decrypt(string s)
{
string dec = "";
char *c1 = new char[s.length()];
d = findIn(e, tot);
char c = '\0';
for (int i = 0; i < s[i] != NULL; i++)
{
int h = s[i];
long long a = ((long long)pow(h, d));
a = a % n;
if (a < 0) a = calcNegativeMod(a, n);
c = a;
dec += c;
c1[i] = (char)a;
c = '\0';
}
return dec;
}
int main()
{
setkeys();
cout << " P is " << p << " \n Q is " << q << endl;
//d = findIn(e, tot);
string en = encrypt("Salman");
string dec = decrypt(en);
cout << " tot is " << tot << endl;
cout << "Encrypted String is " << en << endl;
cout << endl;
cout << "Decrypted String is " << dec << endl;
system("pause");
}
|