-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTTi_encrypter.c
More file actions
1774 lines (1482 loc) · 55.3 KB
/
TTi_encrypter.c
File metadata and controls
1774 lines (1482 loc) · 55.3 KB
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Text to image encrytion decryption
This project converts a text file to a png file encrypting information in it.
- Anshurup gupta
*/
// standard libraries
#include <stdlib.h> //standard library
#include <stdio.h> //standard input/output library
#include <ctype.h> //character classification functions
#include <string.h> //strings
#include <stdbool.h> //booloean macros
#include <time.h> //time library
// imported libraries
#include "FreeImage.h" //image processing
// Definitions
// folder and file addresses relative to root folder
#define word_dictionary "data\\words.txt"
#define data_folder "data\\"
#define data_file "data\\userdat.bin"
#define contact_file "data\\contacts.bin"
#define message_folder "messages\\"
#define decrypt_folder "decrypt\\"
// color definitions
#define KRED "\033[31m" // Error end colors
#define KGRN "\033[32m" // success end colors
#define KYEL "\033[33m" // Warning cause colors
#define KBLU "\033[34m" // message and image contents colors
#define KMAG "\033[35m" // login colors
#define KCYN "\033[36m" // questions colors
#define KWHT "\033[37m" // starting instructions colors
// string limits
#define string_size 30 // normal 30 characters words
#define max_string_size 45 // maximum 45 characters words
#define line_length 2048 // maximum 2048 characters string
// hashing constants
#define hash_bucket_row 250 // hash all words into 250 row buckets
#define hash_bucket_column 256 // hash all words into 256 column buckets
#define max_hash_val 10000000 // maximum possible hash value < 1Cr
// Public_key = ((Private_key << 2) ^ (K_limit)) >> 2 | Z_limit;
#define K_limit 2000 // while making public key k factor be less than 2000
#define Z_limit 204 // z factor less than 204
// structures
typedef struct node // node structures for word
{
char *word; // hold the word
struct node *next; // next node pointer
}node;
typedef struct node_head // node head for nodes
{
short unsigned int collision_count; // counts number of nodes
node *start; // starting node address
}node_head;
typedef struct one_pixel // node structures for single pixels
{
short unsigned int red; // red value of pixel
short unsigned int green; // green value of pixel
short unsigned int blue; // blue value of pixel
struct one_pixel *next_pixel; // next pixel pointer
}one_pixel;
// CONTROL CHANNELS
#define control_border_pixel 251 // (251, , ) -> border pixels
#define control_single_encoding 252 // (252, x, x) -> single character encoding
#define control_double_encoding 253 // (253, y, z) -> double character encoding
#define control_nascii_encoding 254 // (254, y, z) -> non-dictionary words and characters
#define control_start_end_pixel 255 // (255, 0, 91) -> start and end of message pixels
typedef struct sender // public info of sender
{
long long int saved_public_key; // public key of sender
char saved_name[string_size]; // sender's name
int saved_name_hash; // sender's name hashed
}sender;
struct user // user datatype
{
long long int saved_public_key; // saved public data of user
char saved_username[string_size]; // user name
char saved_password[string_size]; // user password
int saved_name_hash; // user name hashed
int saved_private_key; // private key of user
int saved_passkey; // user passkey (only login)
} user_data;
// global variables
// user_data as a struct
// DHA algorithm numbers
const int P_DHA = 9973; // Chosen prime to operate
const int G_DHA = 333; // chosen primitive root
long long int sender_user_common_key = 0; // common key established
// Function Prototypes
// Math functions
int babylon_sqrt(int n); // find square root and round to greatest integer
int Nearest_prime(int n); // finds Nearest prime
long long int a_pow_b_mod_P(int a, int b, int P); // computes (a^b) % P for DHA algorithm
// basic file functions
void Error_message(int i);
bool file_not_exists(char *filepath);
// User data functions
bool datafile_setup(char *path);
int display_contacts(sender **contact_info);
bool add_contact(one_pixel *contact_pixel);
int add_identity(one_pixel *pdata, node_head hash_table_address[hash_bucket_row][hash_bucket_column]);
// mapping and hashing functions
int hash_word(char *string, int offset);
one_pixel *hash_string(char *string, one_pixel *curr_pixel, short unsigned int val, node_head hash_table_address[hash_bucket_row][hash_bucket_column], short unsigned int name_encode);
// loading functions
void node_adder(node_head hash_table_address[hash_bucket_row][hash_bucket_column], char *string, unsigned short int i, unsigned short int j);
bool dict_Loader(node_head hash_table_address[hash_bucket_row][hash_bucket_column]);
int message_Loader(char *filepath, char ***msg_array);
// Encryption & decryption functions
bool encode_key_to_start(one_pixel *head_pixel, char c);
bool decode_key_from_start(one_pixel *head_pixel);
// pixel functions
int txt_to_rgb(char **msg_arry, int size, one_pixel *image_data, node_head hash_table_address[hash_bucket_row][hash_bucket_column], char ans_c);
bool png_to_pixel(unsigned short int i, unsigned short int j, unsigned short int collision, one_pixel *currpixel);
// decoding function
void pixel_dehash(one_pixel *image_data, node_head hash_table_address[hash_bucket_row][hash_bucket_column], char *filesavepath);
// free memory functions
void free_contacts(sender *contact_info);
void free_image_data(one_pixel *image_data1);
void message_Unloader(char ***msg_array, int size);
void dict_Unloader(node_head hash_table_address[hash_bucket_row][hash_bucket_column]);
// main function
int main()
{
// basic variables
int num_lines, contact_num= 0;
short unsigned int count = 0, imgflag = 0;
char passw[string_size], filename[string_size], filepath[max_string_size], ans;
passw[0] = filename[0] = filepath[0] = '\0';
// constant
const int temp_name_length = 10;
// message array
char **message_array;
// contact card of other users
sender *contacts;
// initialise the starting pixel
one_pixel val_image;
{
val_image.red = control_start_end_pixel;
val_image.green = 0;
val_image.blue = 91;
val_image.next_pixel = NULL;
}
int num_pixel = 0, image_square = 0; // image size parameters for encryption
// hash table of node heads and collision counts initialised
node_head hash_table[hash_bucket_row][hash_bucket_column];
for(int x = 0; x < hash_bucket_row; x++)
{
for(int y = 0; y < hash_bucket_column; y++)
{
hash_table[x][y].collision_count = 0;
hash_table[x][y].start = NULL;
}
}
/* Program Starts */
printf(KWHT"\n!Welcome to Text to image encryption and decryption.!\n");
// user data initialisation
if(datafile_setup(data_file))
{
printf(KGRN"\nUser data initialized.\nYou can create your contact card and send to others, to receive encrypted messages.\n");
printf("Your passkey is %d.\nStore it if you forget the password.\nPlease rerun the program.", user_data.saved_passkey);
getchar();
return 0;
}
// user verification
printf(KMAG"\tHello %s,\nEnter your password: ", user_data.saved_username);
//printf(KMAG"\n public key: %lld,\n name hash: %d\n", user_data.saved_public_key, user_data.saved_name_hash);
do
{
if(count)
{
printf(KYEL"Incorrect password.\nRetry: ");
}
if(count == 6)
{
int passkey;
printf(KMAG"\nEnter passkey: ");
scanf("%d%*c", &passkey);
if(passkey != user_data.saved_passkey)
{
printf(KYEL"Delete the userdat.bin file in data folder and re-initialise.\n");
Error_message(2);
}
else
{
break;
}
}
scanf("%[^\n]%*c", &passw);
if(passw[0] == '\0' && count == 0) {printf("blank password triggered.\n");}
count++;
} while (strcmp(user_data.saved_password, passw) && count <= 6);
/** Processing sections **/
printf(KCYN"\nSelect your process from the following:\n");
printf("0 for encrypt:\n\tYou can choose to encrypt for specific person or keep it general.\n");
printf("1 for decrypt:\n\tAutomatic decryption, however words may be gibberish if the message was not intended for you.\n");
printf("2 for user contact card:\n\tTo generate your user card, you need to share your card for others to send you encrypted message.\n");
printf("3 for userdata update:\n\tTo update all data, Previous known contacts must be shared the new cards for further communication.\n");
printf("4 for contacts update:\n\tAdd contacts. To add, you need their contact cards.\n");
printf("Process number: ");
scanf("%c%*c", &ans);
//ans = '2';
printf("\n");
// invalid options end the program
if(ans > '4' || ans < '0') { Error_message(2);}
// process chosen
if(ans == '0')
{
printf(KCYN"\nEnter the name of your message file (max 20 characters long).\nThe file should be present in the messages folder: \n");
scanf("%[^\n]%*c", &filename);
// changes to create the filepath
strcat(filepath, message_folder);
strcat(filename, ".txt");
strcat(filepath, filename);
printf("\n");
if(file_not_exists(filepath))
{
printf(KYEL"%s -> No such files found in messages folder.\n", filename);
Error_message(2);}
// number of contacts available and chosen person
int num_users = 0;
sender one_person;
num_users = display_contacts(&contacts);
if(num_users > 0)
{
printf(KCYN"Enter the number of the person you want to send the encrypted file (0 for no security): \n");
scanf("%d%*c", &contact_num);
}else if(num_users == 0) { contact_num = 0; }
// Set common key used for the encryption according to the user chosen
if(contact_num < 0 || contact_num > num_users)
{
if(num_users < 0) {printf(KYEL"Error in reading contact file.\n"); Error_message(0); }
contact_num = -1;
}
else if(contact_num == 0)
{
sender_user_common_key = 0;
}
else
{
one_person = contacts[contact_num - 1];
sender_user_common_key = a_pow_b_mod_P((int) one_person.saved_public_key, user_data.saved_private_key, P_DHA);
}
printf(KGRN"Encrypting message for %s, Public key: %lld.\nCommon key established: %lld\n",one_person.saved_name, one_person.saved_public_key,sender_user_common_key);
free_contacts(contacts);
if(contact_num < 0) { Error_message(1); }
// load the dictionary only if the file exists and receivers contact is available.
if(dict_Loader(hash_table))
{
Error_message(1);
}
// number of lines present in the message
num_lines = message_Loader(filepath, &message_array);
// Error in loading the message
if(num_lines == 0)
{
dict_Unloader(hash_table);
Error_message(2);
}
else if(num_lines < 0)
{
dict_Unloader(hash_table);
message_Unloader(&message_array, (-1 * num_lines - 1));
Error_message(0);
}
printf(KBLU"Contents of %s file for encrypting:\n\n", filename);
num_pixel = txt_to_rgb(message_array, num_lines, &val_image, hash_table, ans);
//remove filename's extension
filename[strlen(filename) - 4] = '\0';
message_Unloader(&message_array, num_lines);
dict_Unloader(hash_table);
if(num_pixel < 0)
{
Error_message(0);
}
image_square = babylon_sqrt(num_pixel);
//printf("%d\n", image_square);
}
else if(ans == '1')
{
printf(KCYN"\nEnter the name of your image file (max 20 characters long).\nThe image should be present in the decrypt folder: \n");
//strcpy(filename, "output");
scanf("%[^\n]%*c", &filename);
strcat(filepath, decrypt_folder);
strcat(filename, ".png");
strcat(filepath, filename);
printf("\n");
if(file_not_exists(filepath))
{
printf(KYEL"%s -> No such files found in decrypt folder.\n", filename);
Error_message(2);
}
}
else if(ans == '2')
{
encode_key_to_start(&val_image, ans);
one_pixel *end_pixel = (one_pixel *)malloc(sizeof(one_pixel));
{
end_pixel->red = control_start_end_pixel;
end_pixel->green = 0;
end_pixel->blue = 91;
end_pixel->next_pixel = NULL;
}
val_image.next_pixel = end_pixel;
num_lines = add_identity(end_pixel, hash_table);
image_square = babylon_sqrt(num_lines);
if(num_lines < 0)
{
free_image_data(&val_image);
Error_message(0);
}
//printf("%d %d are the values.\n",num_lines, image_square);
}
else if(ans == '3')
{
FILE *newfpw;
int private_key = 0;
printf(KCYN"Enter your updated name (25 characters): ");
scanf("%[^\n]%*c", user_data.saved_username);
printf("Enter your updated password (25 characters): ");
scanf("%[^\n]%*c", user_data.saved_password);
printf("Enter a number for new private key generation (0 < Pri < 1000): ");
scanf("%d%*c", &private_key);
if(user_data.saved_username[0] == '\0' || user_data.saved_password[0] == '\0' || private_key <= 0)
{
Error_message(1);
}
else if(private_key >= 1000)
{
printf(KYEL"Number should be less than 1000.\n");
Error_message(1);
}
user_data.saved_passkey = hash_word(user_data.saved_password, 0);
// only for getting the current time
struct tm* ptr;
time_t lt;
lt = time(NULL);
ptr = localtime(<);
char *user_date = asctime(ptr);
// using the asctime() function to get the time of update.
printf(KMAG"\n%s updated account on %s\n", user_data.saved_username, user_date);
user_data.saved_private_key = ((private_key << 2) ^ (user_data.saved_passkey % K_limit)) >> 2 | (hash_word(user_date, 0) % Z_limit + 1);
user_data.saved_name_hash = hash_word(user_data.saved_username, Nearest_prime(hash_word(user_date, 0)));
user_data.saved_public_key = a_pow_b_mod_P(G_DHA, user_data.saved_private_key, P_DHA);
if(user_data.saved_public_key < 0) {printf(KYEL"Update unsuccessful.\nPlease change the values of private key.\n"); Error_message(0);}
// Update the user data file
newfpw = fopen(data_file, "wb");
if(fwrite(&user_data, sizeof(struct user), 1, newfpw))
{
fclose(newfpw);
}
else{printf(KYEL"Update unsuccessful.\n"); Error_message(0);}
printf(KGRN"\nYour new passkey is %d. Create a new user card and send to all contacts.\n", user_data.saved_passkey);
fclose(newfpw);
}
else if(ans == '4')
{
printf(KCYN"\nEnter the name of your image file (max 20 characters long with -card).\nThe image card should be present in the data folder: \n");
//strcpy(filename, "output");
scanf("%[^\n]%*c", &filename);
strcat(filepath, data_folder);
strcat(filename, ".png");
strcat(filepath, filename);
printf("\n");
if(file_not_exists(filepath))
{
printf(KYEL"No user card found named %s in data folder.\n", filename);
Error_message(1);
}
else if(file_not_exists(contact_file))
{
printf(KWHT"Do not delete the contacts file.\nAll previous contacts lost.\n");
FILE* fp = fopen(contact_file, "wb");
fclose(fp);
}
}
/** Image processing section **/
// Initialize FreeImage library
FreeImage_Initialise(1);
if(ans == '0' || ans == '2')
{
// Create a new image with dimensions for n x n
FIBITMAP *image = FreeImage_Allocate(image_square, image_square, 24, 8, 8, 8);
// Set pixel colors
RGBQUAD color;
one_pixel *temp = &val_image;
for(int r = 0; r < image_square; r++) {
for(int c = 0; c < image_square; c++) {
if(temp != NULL)
{
color.rgbRed = temp -> red;
color.rgbGreen = temp -> green;
color.rgbBlue = temp -> blue;
temp = temp -> next_pixel;
}
else
{
color.rgbRed = control_border_pixel; // Red
color.rgbGreen = 0; // Green
color.rgbBlue = 255; // Blue
}
FreeImage_SetPixelColor(image, c, r, &color);
}
}
// Set compression type to PNG with zero compression
// Save the image
if(ans == '2')
{
//filename
filename[0] = '\0';
char temp_name[temp_name_length];
for(int tn = 0; tn < temp_name_length - 1; tn++) { temp_name[tn] = user_data.saved_username[tn];}
temp_name[temp_name_length] = '\0';
strcpy(filename, strcat(filename,temp_name));
// Set compression type to PNG with zero compression
// Save the image
FreeImage_Save(FIF_PNG, image, strcat(filename,"-card.png"), PNG_Z_NO_COMPRESSION);
}
else
{
FreeImage_Save(FIF_PNG, image, strcat(filename,".png"), PNG_Z_NO_COMPRESSION);
}
// Unload the image
FreeImage_Unload(image);
}
else if(ans == '1' || ans == '4')
{
// Load the PNG image
FIBITMAP* de_image = FreeImage_Load(FIF_PNG, filepath, 0);
// Check if the image was loaded successfully
if (de_image) {
// Get image dimensions
unsigned width = FreeImage_GetWidth(de_image);
unsigned height = FreeImage_GetHeight(de_image);
RGBQUAD pixelColor;
one_pixel *temp_pixel = &val_image;
// Iterate over the image pixels
for (unsigned y = 0; y < height; y++) {
for (unsigned x = 0; x < width; x++) {
// Get the color of the current pixel
if (FreeImage_GetPixelColor(de_image, x, y, &pixelColor)) {
// Print the RGB values of the pixel
//printf(KBLU"Pixel (%u, %u): [%u %u %u]\n", x, y, pixelColor.rgbRed, pixelColor.rgbGreen, pixelColor.rgbBlue);
if(pixelColor.rgbRed != control_border_pixel && png_to_pixel(pixelColor.rgbRed, pixelColor.rgbGreen, pixelColor.rgbBlue, temp_pixel))
{ temp_pixel = temp_pixel -> next_pixel; }
else if(pixelColor.rgbRed != control_border_pixel)
{
imgflag = 1;
printf(KYEL"Image not accesible.\nMessage cannot be decrypted.\n");
break;
}
}
}
if(imgflag) { break; }
}
// Unload the image when done
FreeImage_Unload(de_image);
//remove filename's extension
filename[strlen(filename) - 4] = '\0';
// load the dictionary file after decoding the key
if(ans == '1' && decode_key_from_start(val_image.next_pixel) && dict_Loader(hash_table))
{
free_image_data(&val_image);
Error_message(1);
}
// make the text file
if(!imgflag)
{
if(ans == '1')
{
pixel_dehash(&val_image, hash_table, strcat(filename, ".txt"));
}
else
{
if(!add_contact(val_image.next_pixel))
{
imgflag = 1;
}
}
}
}
else { printf(KYEL"Failed to load the image.\n"); imgflag = 1;}
}
// Deinitialize FreeImage library
FreeImage_DeInitialise();
if(ans == '1') { dict_Unloader(hash_table); }
if(ans != '3') { free_image_data(&val_image); }
if(imgflag){ Error_message(0); }
printf(KGRN"\n!Program terminated successfully!\nPress enter to exit.");
getchar();
return 0;
}
// Function Definitions
// sqrt round off for sqare base of image
int babylon_sqrt(int n)
{
float ans = 0.0001;
float x1 = 0, x2 = 0;
x1 = (n + 1) / 2.0;
x2 = (x1 + n / x1) / 2.0;
while(x1 - x2 >= ans && x1 - x2 > 0)
{
x1 = (x1 + n / x1) / 2.0;
x2 = (x1 + n / x1) / 2.0;
}
int val = x2;
if(val - x2 >= 0)
{
return val;
}
else
{
return (val + 1);
}
}
// Find nearest Prime of n
int Nearest_prime(int n)
{
bool yes_prime = true;
int num = n;
int root_n = 1;
do
{
yes_prime = true;
root_n = babylon_sqrt(num);
if(num % 2 == 0)
{
yes_prime = false;
}
else
{
for(int i = 3; i < root_n + 1; i += 2)
{
if(num % i == 0)
{
yes_prime = false;
break;
}
}
}
if(yes_prime)
{
break;
}
else
{
num--;
}
} while (num);
return num;
}
// a^b % P computation
long long int a_pow_b_mod_P(int a, int b, int P)
{
long long int r = 1;
long long int x = a % P;
int n_power = b;
while(n_power > 0)
{
if(n_power % 2 == 1)
{
r = (r * x) % P;
}
x = (x * x) % P;
n_power = n_power / 2;
}
if(r < 0)
{
printf(KYEL"Computation not possible.\n");
}
return r;
}
//error message
void Error_message(int i)
{
printf(KRED"\n***Error***\n");
//switch case for different messages
switch (i)
{
case 1:
printf("Files or data failed to load.");
break;
case 2:
printf("Invalid User input.\nPlease use proper inputs.");
break;
default:
printf("Unknow cause of error in program.");
break;
}
printf("\n\nPlease close other programs and rerun.\nProgram is terminated. Press enter to exit.\n***Error***");
getchar();
//exit out as program under control
exit(0);
}
// whether a file exists or not
bool file_not_exists(char *filepath)
{
bool val;
FILE *fp;
char file_exe[5]; // for checking extension
int len = strlen(filepath);
for(int i = 0; i < 5; i++)
{
file_exe[i] = filepath[len + i - 4];
}
if(!strcmp(file_exe, ".bin")) // binary file check
{
fp = fopen(filepath, "rb");
}
else if(!strcmp(file_exe, ".txt")) // txt file check
{
fp = fopen(filepath, "r");
}
else if(!strcmp(file_exe, ".png")) // png file check
{
fp = fopen(filepath, "r");
}
else
{
printf(KYEL"\nInvalid file type %s.\nMessage files should be in .txt\nImage files should be in .png.\n", file_exe);
Error_message(1);
}
if(fp == NULL)
{
val = true;
}
else
{
val = false;
}
fclose(fp);
return val;
}
// check if user data file is setup or not
bool datafile_setup(char *path)
{
int private_key;
FILE *fpr = fopen(path, "rb");
FILE *fpw, *fcw;
if(fpr == NULL)
{
fclose(fpr);
printf(KMAG"Enter your name (25 characters): ");
scanf("%[^\n]%*c", user_data.saved_username);
printf("Enter your password (25 characters): ");
scanf("%[^\n]%*c", user_data.saved_password);
printf("Enter a number for private key generation (0 < Pri < 1000): ");
scanf("%d%*c", &private_key);
if(user_data.saved_username[0] == '\0' || user_data.saved_password[0] == '\0' || private_key <= 0)
{
Error_message(1);
}
else if(private_key >= 1000)
{
printf("Number should be less than 1000.\n");
Error_message(1);
}
user_data.saved_passkey = hash_word(user_data.saved_password, 0);
// only for getting the current time
struct tm* ptr;
time_t lt;
lt = time(NULL);
ptr = localtime(<);
char *user_date = asctime(ptr);
// using the asctime() function to get the time of initialisation.
printf("\n%s created account on %s\n", user_data.saved_username, user_date);
user_data.saved_private_key = ((private_key << 2) ^ (user_data.saved_passkey % K_limit)) >> 2 | (hash_word(user_date, 0) % Z_limit + 1);
user_data.saved_name_hash = hash_word(user_data.saved_username, Nearest_prime(hash_word(user_date, 0)));
user_data.saved_public_key = a_pow_b_mod_P(G_DHA, user_data.saved_private_key, P_DHA);
if(user_data.saved_public_key < 0) {printf(KYEL"Unable to create profile.\nPlease change the values of private key.\n"); Error_message(0);}
printf("\nname hash %d private key %d public key %lld\n", user_data.saved_name_hash, user_data.saved_private_key, user_data.saved_public_key);
fpw = fopen(path, "wb");
if(fpw == NULL)
{
fclose(fpw);
Error_message(1);
}
fcw = fopen(contact_file, "rb");
if(fcw == NULL){ fcw = fopen(contact_file, "wb"); }
fclose(fcw);
if(fwrite(&user_data, sizeof(struct user), 1, fpw))
{
fclose(fpw);
}
else{Error_message(0);}
return true;
}
fread(&user_data, sizeof(struct user), 1, fpr);
fclose(fpr);
return false;
}
// Displays saved user contacts
int display_contacts(sender **contact_info)
{
long int pos;
int number_con = 0;
FILE *fp = fopen(contact_file, "rb");
if(fp == NULL)
{
printf(KYEL"Contacts file corrupted or not present.\n");
return -1;
}
fseek(fp, 0, SEEK_END);
pos = ftell(fp);
number_con = pos / sizeof(sender);
*contact_info = (sender *)malloc(number_con * sizeof(sender));
if(contact_info == NULL){fclose(fp); Error_message(0); }
if(pos < 1 || number_con < 1) { printf(KWHT"No contacts found.\nSwitching to General encryption.\n"); fclose(fp); return 0; }
fseek(fp, 0, SEEK_SET);
printf("%d %d %ld\n", pos, number_con, sizeof(sender));
for(int i = 0; i < number_con; i++)
{
sender person;
fread(&person, sizeof(sender), 1, fp);
printf(KGRN"%d)Name: %s\nName_hash: %d\n", i + 1, (person.saved_name), (person.saved_name_hash));
printf("public key: %lld\n", (person.saved_public_key));
printf("\n");
(*contact_info)[i] = person;
}
fclose(fp);
return number_con;
}
// Adds a single contact of user
bool add_contact(one_pixel *contact_pixel)
{
char c = '\0', name_holder[string_size];
name_holder[0] = '\0';
sender new_person;
int counter = 0, len = 0;
one_pixel *temp = contact_pixel;
while(temp != NULL)
{
if(temp -> next_pixel == NULL)
{
new_person.saved_name_hash = (temp->red * control_start_end_pixel * control_start_end_pixel + temp->green * control_start_end_pixel + temp->blue);
}
else
{
if(temp -> red == control_start_end_pixel)
{
if(counter == 0)
{
new_person.saved_public_key = (temp->green * control_start_end_pixel + temp->blue);
}
counter++;
}
else if(temp->red == control_nascii_encoding && counter == 2)
{
c = (char)(temp->green);
name_holder[len] = c;
if(temp->blue > 0)
{
len++;
c = (char)(temp->blue);
name_holder[len] = c;
}
len++;
}
if(counter == 3)
{
name_holder[len] = '\0';
}
}
temp = temp -> next_pixel;
}
if(len > string_size || new_person.saved_public_key < 0)
{
printf(KYEL"Error in reading card.\n");
return false;
}
strcpy(new_person.saved_name, name_holder);
FILE *fp = fopen(contact_file, "ab");
if(fp == NULL){ fclose(fp); return false; }
fseek(fp, 0, SEEK_END);
if(!fwrite(&new_person, sizeof(sender), 1, fp))
{ fclose(fp); return false; }
printf(KGRN"\nNew contact added.\n");
printf("Name: %s\nPublic_key: %lld\nName_hash: %d\n", new_person.saved_name, new_person.saved_public_key, new_person.saved_name_hash);
fclose(fp);
return true;
}
// adds identity after a specific pixel segment
int add_identity(one_pixel *pdata,node_head hash_table_address[hash_bucket_row][hash_bucket_column])
{
int count = 1;
one_pixel* temp = hash_string(user_data.saved_username, pdata, 0, hash_table_address, 1);
// save name hash in base 255
one_pixel* endnum = (one_pixel *)malloc(sizeof(one_pixel));
if(endnum == NULL){ return -1; }
{
endnum->red = ((user_data.saved_name_hash - user_data.saved_name_hash % (control_start_end_pixel * control_start_end_pixel)) / (control_start_end_pixel * control_start_end_pixel));
endnum->green = ((user_data.saved_name_hash - user_data.saved_name_hash % control_start_end_pixel) / control_start_end_pixel);
endnum->blue = (user_data.saved_name_hash % control_start_end_pixel);
endnum->next_pixel = NULL;
}
one_pixel *end_pixel = (one_pixel *)malloc(sizeof(one_pixel));
if(end_pixel == NULL){ return -1; }
{
end_pixel->red = control_start_end_pixel;
end_pixel->green = 0;
end_pixel->blue = 91;
end_pixel->next_pixel = endnum;
}
temp -> next_pixel = end_pixel;
temp = pdata;
while(temp != NULL)
{
count++;
//printf("%d) %p [%d %d %d] -> %p\n", count, temp,temp->red,temp->green,temp->blue,temp->next_pixel);
temp = temp ->next_pixel;
}
return count;
}
/*
for mapping 2 alphabet letters
it starts from 98 goes to 123
*/
// hash function !* Important *!
int hash_word(char *string, int offset)
{
int hash_val = 0;
int l = strlen(string);
hash_val = 2 * l;
for(int i = 0; i < l; i++)