-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRSAEncryption.cc
347 lines (309 loc) · 8.32 KB
/
RSAEncryption.cc
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#include "RSAEncryption.hh"
#include "BigIntegerAlgorithms.hh"
#include "BigIntegerUtils.hh"
#include "BigUnsignedInABase.hh"
#include <thread>
#include <time.h>
#include <random>
#include <stdio.h>
RSAEncryption::RSAEncryption()
{
}
RSAEncryption::~RSAEncryption()
{
}
bool RSAEncryption::verifyFile(std::string myFileToCheck, std::string mySignature)
{
struct stat myStat;
if (stat(myFileToCheck.c_str(), &myStat) != 0)
{
cout << "File: " << myFileToCheck << endl;
}
ifstream mySignedFile(mySignature, ios::binary);
string EncryptedText;
getline(mySignedFile, EncryptedText);
cout << EncryptedText << "NO RETURN";
if (!AttemptToLoadKeys())
{
cout << "Attempted to open key files failed!" << endl;
return false;
};
mySignedFile.close();
BigUnsigned myDecryptedSHA = stringToBigUnsigned(EncryptedText);
myDecryptedSHA = encryptBytes(myDecryptedSHA);
ifstream input(myFileToCheck, ios::binary);
input.seekg(0, input.end);
size_t mySize = input.tellg();
char *myCharacter = new char[mySize];
input.seekg(0, input.beg);
input.read(myCharacter, mySize);
input.close();
std::string mySha = sha256(myCharacter, mySize);
delete myCharacter;
BigUnsigned Converted = BigUnsignedInABase(mySha, 16);
//cout << "myCOnvertedBase =" << Converted << endl;
//cout << "myDecryptedSHA =" << myDecryptedSHA;
if (Converted == myDecryptedSHA)
{
cout << endl << endl << "File Verified!" << endl << endl;
return true;
}
else {
cout << "Failed to verify file!" << endl;;
PrintError();
return false;
}
}
void RSAEncryption::signFile(string FileLocation)
{
if (!AttemptToLoadKeys())
{
cout << "Error: could not find keys!" << endl;
return;
}
struct stat myStuff;
if (stat(FileLocation.c_str(), &myStuff) != 0)
{
FileLocation = ".\\" + FileLocation;
if (stat(FileLocation.c_str(), &myStuff) != 0)
{
cout << "Failed to find file: " + FileLocation;
return;
}
}
std::ifstream input(FileLocation, ios::binary);
input.seekg(0, input.end);
size_t mySize = input.tellg();
char *myCharacter = new char[mySize + 1];
input.seekg(0, input.beg);
input.read(myCharacter, mySize);
input.close();
string mySHA = sha256(myCharacter, mySize);
BigUnsigned myConverted = BigUnsignedInABase(mySHA, 16);
cout << "SHA that we signed: " << myConverted << endl << endl;
myConverted = decryptBytes(myConverted);//shortend, might break;
std::ofstream output(FileLocation + ".signed", std::ios::binary);
output << myConverted;
output.flush();
output.close();
delete myCharacter;
}
void RSAEncryption::createRSAKeys(int bits)
{
vector<std::future<BigUnsigned>> MyFutures;
int myKeySize = bits / 2;
unsigned concurrentThreadsSupported = std::thread::hardware_concurrency();
cout << "Generating 2 keys of size " << myKeySize << " bits using " << concurrentThreadsSupported << "threads:";
clock_t encryptionTimeCompletionTime = clock();
if (concurrentThreadsSupported < 2)
{
myQ = generatePrime(myKeySize);
myP = generatePrime(myKeySize);
}
else {
for (int i = 0; i < concurrentThreadsSupported; i++)
{
std::packaged_task<BigUnsigned(int)> Calculate(generatePrime);
MyFutures.push_back(Calculate.get_future());
thread myPrimePCalculator(std::move(Calculate), myKeySize);
myPrimePCalculator.detach();
}
}
if (MyFutures.size() != 0)
{
int FoundPrimes = 0;
std::chrono::milliseconds span(1);
FoundPrimes = 0;
while (FoundPrimes < 2)
{
for (auto i = MyFutures.begin(); i != MyFutures.end(); i++)
{
if ((*i).wait_for(span) == std::future_status::ready)
{
if (myP == 0)
{
myP = (*i).get();
}
else
{
myQ = (*i).get();
}
FoundPrimes++;
i = MyFutures.erase(i);
//TO prevent passing the future it.
if (i == MyFutures.end())
{
i--;
continue;
}
}
}
}
}
assert(myP != myQ);
cout << "..";
cout << ".." << endl;
encryptionTimeCompletionTime = clock() - encryptionTimeCompletionTime;
float ms = double(encryptionTimeCompletionTime) / CLOCKS_PER_SEC * 1000;
cout << endl << endl << "Time to complete in MS" << ms << endl;
maxEncryptableCharacters = ceil(bits / 8);
cout << "Max encryptable bits: " << maxEncryptableCharacters << endl;
cout << "Now calculating D and E: " << endl;
calculateDAndE();
cout << "Writing to File: " << endl << endl;
writePublicKey();
writePrivateKey();
WritePrimes();
}
bool RSAEncryption::AttemptToLoadKeys()
{
struct stat buffer;
if (stat("d_n.txt", &buffer) != 0)
{
return false;
}
if (stat("e_n.txt", &buffer) != 0)
{
return false;
}
std::ifstream input("d_n.txt", ios::binary);
string lineOne;
getline(input, lineOne);
myD = stringToBigUnsigned(lineOne);
getline(input, lineOne);
myN = stringToBigUnsigned(lineOne);
input.close();
std::ifstream input2("e_n.txt", ios::binary);
getline(input2, lineOne);
myE = stringToBigUnsigned(lineOne);
input2.close();
return true;
}
void RSAEncryption::PrintError()
{
cout << "My E: " << endl << bigUnsignedToString(myE) << endl << endl;
cout << "My D: " << endl << bigUnsignedToString(myD) << endl << endl;
cout << "My N: " << endl << bigUnsignedToString(myN) << endl << endl;
}
void RSAEncryption::calculateDAndE()
{
myN = (myP)*(myQ);
BigUnsigned totient = (myP - 1)*(myQ - 1);
BigInteger myG;
BigInteger myR;
BigInteger MyTemp;
BigInteger MyTempD;
for (BigUnsigned i = rand() % 1000000; i < myN; i++)
{//rs = x y
extendedEuclidean(i, totient, myG, MyTempD, MyTemp);
if ((myG) == 1)
{
myE = i;
myD = modinv(myE, totient);
break;
}
}
}
bool RSAEncryption::isPrime(BigUnsigned n)
{
int testCount = 3;
for (BigUnsigned i = 5; i < n; i++)
{
if (gcd(i, n) == 1) //if our i is co prime
{
testCount--;
//cout << i;
BigUnsigned RetVal = modexp(i, (n - 1), n);
//cout << "Retval for " << n << " equals " << RetVal << endl;
if (RetVal != 1) return false;
if (testCount == 0) break;
}
}
return true;
}
BigUnsigned RSAEncryption::generatePrime(int SizeInBits)
{
std::random_device rd;
std::uniform_int_distribution<int> distribution(0, 10);
BigUnsigned A;
std::string myString;
A = 2;
do
{
myString = "";
for (int i = 0; i < ceil(log10(pow(2, SizeInBits))); i++)
{
myString.append(to_string(distribution(rd)));
}
A = stringToBigUnsigned(myString);
//cout << A << endl << endl;
} while (!isPrime(A));// || A > (2 ^ SizeInBits) - 1);
//cout << "IS PRIME TEST: " << isPrime(A) << endl;
return A;
}
void RSAEncryption::part1OfProject()
{
createRSAKeys(1024);
WritePrimes();
writePrivateKey();
writePublicKey();
}
BigUnsigned RSAEncryption::encryptBytes(BigUnsigned encryptText)
{
cout << "Clear Text: " << encryptText << endl << endl;
BigUnsigned Encrypted = modexp(encryptText, myE, myN);
cout << "Encrypted Text: " << Encrypted << endl << endl;
return Encrypted;
}
BigUnsigned RSAEncryption::decryptBytes(BigUnsigned Data)
{
cout << "Encrypted Text: " << Data << endl << endl;
BigUnsigned myReturnedString = modexp(Data, myD, myN);
cout << "Clear Text: " << myReturnedString << endl << endl;
return myReturnedString;
}
void RSAEncryption::WritePrimes()
{
ofstream myPrimeStream("p_q.txt", iostream::binary);
if (myPrimeStream.fail())
{
cout << "Failed to write primes in file!";
}
std::string myPString = bigUnsignedToString(myP);
myPString += "\n";
myPrimeStream.write(myPString.c_str(), myPString.length());
std::string myQString = bigUnsignedToString(myQ);
myPrimeStream.write(myQString.c_str(), myQString.length());
myPrimeStream.flush();
myPrimeStream.close();
}
void RSAEncryption::writePrivateKey()
{
ofstream myPrimeStream("d_n.txt", iostream::binary);
if (myPrimeStream.fail())
{
cout << "Failed to write d_n in file!";
}
std::string myPString = bigIntegerToString(myD);
myPString += "\n";
myPrimeStream.write(myPString.c_str(), myPString.length());
std::string myQString = bigUnsignedToString(myN);
myPrimeStream.write(myQString.c_str(), myQString.length());
myPrimeStream.flush();
myPrimeStream.close();
}
void RSAEncryption::writePublicKey()
{
ofstream myPrimeStream("e_n.txt", iostream::binary);
if (myPrimeStream.fail())
{
cout << "Failed to write e_n in file!";
}
std::string myPString = bigUnsignedToString(myE);
myPString += "\n";
myPrimeStream.write(myPString.c_str(), myPString.length());
std::string myQString = bigUnsignedToString(myN);
myPrimeStream.write(myQString.c_str(), myQString.length());
myPrimeStream.flush();
myPrimeStream.close();
}