Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include "functions.h"
- #define ALPHABET_LENGTH 26
- static char ReverseAlphabet[ALPHABET_LENGTH] = {
- 'Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A'
- };
- static char Alphabet[ALPHABET_LENGTH] = {
- 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
- };
- char *remove_duplicates(char *table)
- {
- char flag[208] = {0};
- int i, j = 0;
- for (i = 0; table[i] != '\0'; i++) {
- if (0 == flag[table[i]]) {
- flag[table[i]] = 1;
- table[j] = table[i];
- j++;
- }
- }
- table[j] = '\0';
- return NULL;
- }
- int function_encrypt(char *key, char *inFileData, char *outFileName, int size)
- {
- FILE *file = fopen(outFileName, "w");
- int maxlen = (int)strlen(key) + ALPHABET_LENGTH;
- char out_data[size + 1];
- char *substitutionTable = (char*)malloc(maxlen);
- if (substitutionTable) {
- // create the following:
- // 'K','E','Y','Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A'
- strcpy(substitutionTable, key);
- strcat(substitutionTable, ReverseAlphabet);
- remove_duplicates(substitutionTable);
- for (int i = 0 ; i < strlen(inFileData); i++) {
- out_data[i] = substitutionTable[inFileData[i] - 'A'];
- }
- out_data[size] = '\0';
- free(substitutionTable);
- int val = fputs(out_data,file);
- if (val >= 0 ) {
- printf("\nSuccess");
- fclose(file);
- }
- else {
- printf("\nFailed");
- }
- return 0;
- }
- return -1; // return error
- }
- int function_decrypt(char *key, char *inFileData, char *outFileName, int size)
- {
- FILE *file = fopen(outFileName, "w");
- int maxlen = (int)strlen(key) + ALPHABET_LENGTH;
- char out_data[size + 1];
- char *substitutionTable = (char*)malloc(maxlen);
- if (substitutionTable) {
- // create the following:
- // 'K','E','Y','Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A'
- strcpy(substitutionTable, key);
- strcat(substitutionTable, ReverseAlphabet);
- remove_duplicates(substitutionTable);
- for (int i = 0 ; i < strlen(inFileData); i++) {
- const char *ptr = strchr(substitutionTable, inFileData[i]);
- if(ptr) {
- int index = ptr - substitutionTable;
- out_data[i] = Alphabet[index];
- }
- }
- out_data[size] = '\0';
- free(substitutionTable);
- int val = fputs(out_data,file);
- if (val >= 0 ) {
- printf("\nSuccess");
- fclose(file);
- }
- else {
- printf("\nFailed");
- }
- return 0;
- }
- return -1; // return error
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement