-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.cpp
500 lines (429 loc) · 15.5 KB
/
utility.cpp
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#include "utility.h"
#include "crypto++/cryptlib.h"
#include "crypto++/rsa.h"
#include "crypto++/sha.h"
#include "crypto++/hex.h"
#include "crypto++/aes.h"
#include "crypto++/modes.h"
#include "crypto++/filters.h"
#include "crypto++/osrng.h"
#include "crypto++/files.h"
#include "crypto++/base64.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
using namespace CryptoPP;
/*
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
Hash Functions
*/
string computeHash(const string& data){
byte const* byteData = (byte*)data.data();
unsigned int nDataLen = data.size();
byte digest[SHA256::DIGESTSIZE];
SHA256().CalculateDigest(digest, byteData, nDataLen);
stringstream ss;
for (int i = 0; i < SHA256::DIGESTSIZE; i++)
ss << hex << (int)digest[i];
return ss.str();
}
// hash a string and attach the hash to the end of the string
void addHash(string& data){
data.append("TheHash:");
data.append(computeHash(data));
}
// compare hash at end of file to newly computed hash. data is information to be hashed. existing hash is hash at end of file
void checkHash(string data, string existingHash) {
// set up hash
byte const* byteData = (byte*)data.data();
unsigned int nDataLen = data.size();
byte digest[SHA256::DIGESTSIZE];
SHA256().CalculateDigest(digest, byteData, nDataLen);
// convert digest into a string to be compared
string newHash = btos(digest, SHA256::DIGESTSIZE);
/*cout << "Hash of file received: " << newHash << ". Length: " << newHash.length() << endl;
cout << "Hash in the file: " << existingHash << ". Length: " << existingHash.length() << endl;*/
bool same = true;
for (size_t i = 0; i < newHash.length(); i++) {
if (newHash[i] != existingHash[i]) {
bool same = false;
break;
}
}
if (same)
cout << "Message authentic.\n";
else
cout << "Message unauthentic.\n";
// existing hash is always 1 more than newHash for some reason length wise even though they output identical
/*if (newHash == existingHash)
cout << "Message authentic.\n";
else
cout << "Message unauthentic.\n";*/
}
/*
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
AES Functions
*/
AESParams genAESParams(){
AESParams params;
AutoSeededRandomPool rnd;
SecByteBlock key(0x00, AES::DEFAULT_KEYLENGTH);
SecByteBlock iv(0x00, AES::BLOCKSIZE);
rnd.GenerateBlock(iv, AES::BLOCKSIZE);
rnd.GenerateBlock(key, AES::DEFAULT_KEYLENGTH);
params.key = key;
params.iv = iv;
return params;
}
// encrypt data (file contents) and write to new file
string AESEncrypt(SecByteBlock& key, SecByteBlock& iv, string data) {
// create cipher
string ciphertext;
AES::Encryption aesEncryption(key, AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);
StreamTransformationFilter stfEncryptor(cbcEncryption, new StringSink(ciphertext));
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(data.c_str()), data.length() + 1);
stfEncryptor.MessageEnd();
// hex encode ciphertext and write to file
string encoded;
HexEncoder encoder(new StringSink(encoded));
encoder.Put((byte*)ciphertext.data(), ciphertext.size());
encoder.MessageEnd();
return encoded;
}
// decrypt an encrypted string. does not have line breaks
string AESDecrypt(string& keyString, string& ivString, string& encryption){
SecByteBlock key((byte *)(keyString.data()), keyString.size());
SecByteBlock iv((byte *)(ivString.data()), ivString.size());
// hex decode the message
string decoded = htos(encryption);
AES::Decryption aesDecryption(key, AES::DEFAULT_KEYLENGTH);
//CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, (byte *)ivString.data());
CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv.data());
string decryption;
StreamTransformationFilter stfDecryptor(cbcDecryption, new StringSink(decryption));
stfDecryptor.Put(reinterpret_cast<const unsigned char*>(decoded.c_str()), decoded.size());
stfDecryptor.MessageEnd();
// divide decryption into message and hash
size_t findHash = decryption.find("TheHash:");
string decryptNoHash = decryption.substr(0, findHash);
string hash = decryption.substr(findHash + 8);
// check the two hashes
checkHash(decryptNoHash, hash);
return decryptNoHash;
}
/*
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
RSA Functions
*/
RSAKeys genRSAKeys(){
AutoSeededRandomPool rnd;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rnd, 16000);
RSAKeys keys;
keys.privateKey = new RSA::PrivateKey(params);
keys.publicKey = new RSA::PublicKey(params);
/*
//Test code
saveRSAPriKey(*(keys.privateKey), "private");
saveRSAPubKey(*(keys.publicKey), "public");
ifstream ipub("private");
string pubKey;
getline(ipub, pubKey, (char)ipub.eof());
ipub.close();
ofstream opub("private1");
opub << pubKey;
opub.close();
RSA::PublicKey pubK;
RSA::PrivateKey privK;
loadRSAPubKey(pubK, "public");
loadRSAPriKey(privK, "private1");
string plain = "RSA Encryption";
string cipher = RSAEncrypt(pubK, plain);
cout << cipher << endl;
string recovered = RSADecrypt(privK, cipher);
cout << recovered << endl;
*/
return keys;
}
void saveRSAPubKey(RSA::PublicKey& key, const char* filename){
Base64Encoder publicKey(new FileSink(filename));
key.DEREncode(publicKey);
publicKey.MessageEnd();
}
void saveRSAPriKey(RSA::PrivateKey& key, const char* filename){
Base64Encoder privateKey(new FileSink(filename));
key.DEREncode(privateKey);
privateKey.MessageEnd();
}
void loadRSAPubKey(RSA::PublicKey& key, const char* filename){
ByteQueue byte;
FileSource file(filename, true, new Base64Decoder);
file.TransferTo(byte);
byte.MessageEnd();
key.Load(byte);
}
void loadRSAPriKey(RSA::PrivateKey& key, const char* filename){
ByteQueue byte;
FileSource file(filename, true, new Base64Decoder);
file.TransferTo(byte);
byte.MessageEnd();
key.Load(byte);
}
string RSAEncrypt(RSA::PublicKey pubK, string& data){
AutoSeededRandomPool rnd;
string cipher;
RSAES_OAEP_SHA_Encryptor e(pubK);
StringSource ss(data, true,
new PK_EncryptorFilter(rnd, e,
new StringSink(cipher)
)
);
return cipher;
}
string RSADecrypt(RSA::PrivateKey privK, string& cipher){
AutoSeededRandomPool rnd;
string plaintext;
RSAES_OAEP_SHA_Decryptor d(privK);
StringSource ss(cipher, true,
new PK_DecryptorFilter(rnd, d,
new StringSink(plaintext)
)
);
return plaintext;
}
/*
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
***********************************************************************************
Helper Functions
*/
int prompt(string& fileName) {
bool chosen = false;
int finalResponse;
// user chooses whether they want to save a file or get contents of one
while (!chosen) {
cout << "Press 1 to save a file, 2 to retrieve a file or 3 to quit. ";
int tempResponse;
cin >> tempResponse;
if (tempResponse == 1 || tempResponse == 2 || tempResponse == 3) {
chosen = true;
finalResponse = tempResponse;
}
else {
cout << "Invalid response. Please try again.\n";
cin.clear();
cin.ignore(100, '\n');
}
}
if (finalResponse != 3) {
cout << "Enter in the file you wish to access: ";
cin >> fileName;
}
return finalResponse;
}
// convert byte* into a readable string
string btos(byte* data, int len){
stringstream ss;
ss << hex;
for (int i = 0; i < len; ++i)
ss << (int)data[i];
return ss.str();
}
string htos(string &hex){
string str;
HexDecoder decoder1(new StringSink(str));
decoder1.Put((byte*)hex.data(), hex.size());
decoder1.MessageEnd();
return str;
}
string btoh(string &bytes){
string hex;
HexEncoder encoder(new StringSink(hex));
encoder.Put((byte*)bytes.data(), bytes.size());
encoder.MessageEnd();
return hex;
}
string btoh(SecByteBlock& bytes){
string hex;
HexEncoder encoder(new StringSink(hex));
encoder.Put((byte*)bytes.data(), bytes.size());
encoder.MessageEnd();
return hex;
}
//Reads in user input
void getInput(char *name, int size){
//Read input from stdin
int len = read(STDIN_FILENO, name, size);
if (len == -1) { perror("Faile to get user input"); }
//Remove newline character
name[len - 1] = '\0';
}
//Reads in port number
int getPortNum(){
char buf[BUF_SIZE];
getInput(buf, BUF_SIZE);
char *endptr;
int portNum = strtol(buf, &endptr, 10);
if (*endptr != '\0') { perror("Invalid input for port number"); }
return portNum;
}
//Reads in packet of data including header and data
void readData(int connfd, char *buff, int size){
//Extract header
char header[8];
int len = read(connfd, header, 8);
if (len != 8) return;
for (int i = 0; i < 8; ++i) {
if (header[i] == '-') {
header[i] = '\0';
break;
}
}
//Read number of characters based on length provided by header
int length = atoi(header);
int i = 0;
char tmp[1];
while (i < length) {
read(connfd, tmp, 1);
buff[i] = tmp[0];
++i;
}
buff[i] = '\0';
cout << "Received: " << header << buff << endl;
}
//Writes message with header and data
void writeData(int connfd, const char *buff, int size){
//Add header to msg
char msg[BUF_SIZE];
snprintf(msg, 8, "%d", size);
while (strlen(msg) != 8) {
strcat(msg, "-");
}
strcat(msg, buff);
int length = strlen(msg);
if (length != write(connfd, msg, length)) {
cout << "Write has failed\n";
}
cout << "Sent: " << msg << endl;
}
void getPublicKey(const char* name, const char *ip, int port){
//Create socket
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) { perror("Failed to create socket fd"); }
//Create sockaddr_in to store socket information
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
//Convert dotted decimal address to network address structure and place in sockaddr
int res = inet_pton(AF_INET, ip, &sockaddr.sin_addr);
if (res == 0) { perror("Invalid network address"); }
if (res == -1) { perror("Invalid address family"); }
//Specify port used to connect to server
sockaddr.sin_port = htons(port);
//Connect to the server
if (connect(fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr)) == -1) {
perror("Failed to connect to CA");
}
else { printf("Successfully connected to CA\n"); }
/*
RSA::PublicKey CAKey;
loadRSAPubKey(CAKey, computeHash("CAKey").c_str());
string msg(name);
msg.append("\nclientKey");
string cipher = RSAEncrypt(CAKey, msg);
string request = btoh(cipher);
//Request server public key from CA
writeData(fd, request.c_str(), request.length());
*/
sendRSAData(fd, "serverKey", "client", "CA");
string message = rcvRSAData(fd);
istringstream iss(message);
string key;
iss >> key >> key;
//Store server public key in a file
ofstream ofs(computeHash("serverKey"));
ofs << key;
ofs.close();
}
void sendRSAData(int fd, const char* buf, const char* sender, const char* rcvr){
string keyName(rcvr);
keyName.append("Key");
RSA::PublicKey pubKey;
loadRSAPubKey(pubKey, computeHash(keyName).c_str());
string msg(sender);
msg += "\n";
msg.append(buf);
string cipher = RSAEncrypt(pubKey, msg);
string request = btoh(cipher);
writeData(fd, request.c_str(), request.length());
}
string rcvRSAData(int fd){
char buf[BUF_SIZE];
readData(fd, buf, BUF_SIZE);
string cipher(buf);
RSA::PrivateKey privK;
loadRSAPriKey(privK, computeHash("myKey").c_str());
string bytes = htos(cipher);
string plaintext = RSADecrypt(privK, bytes);
return plaintext;
}
void sendPublicKey(int fd, const string& keyNeeded, const string& sender, const string& rcvr){
ifstream ifs(computeHash(keyNeeded));
string key;
getline(ifs, key, (char)ifs.eof());
sendRSAData(fd, key.c_str(), sender.c_str(), rcvr.c_str());
writeData(fd, key.c_str(), key.length());
}