Last active
April 15, 2021 18:54
-
-
Save DreamVB/6e89f0fca978b703d885ed1ead112c78 to your computer and use it in GitHub Desktop.
XOR File using c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _CRT_SECURE_NO_WARNINGS | |
#include <stdio.h> | |
#include <string> | |
int PasswordKey(char *pws){ | |
int x = 0; | |
size_t i = 0; | |
x = 1586; | |
while (pws[i]){ | |
x += (int)pws[i]; | |
i++; | |
} | |
return x; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
FILE *fp1 = nullptr; | |
FILE *fp2 = nullptr; | |
char c = '\0'; | |
int key = 0; | |
//Check syntax of command | |
if (argc < 4){ | |
fprintf(stdout, "Usage input-file output-file password.\n"); | |
return EXIT_FAILURE; | |
} | |
//Check for password | |
if (strlen(argv[3]) == 0){ | |
fprintf(stdout,"Password Required.\n"); | |
return EXIT_FAILURE; | |
} | |
//Open input file. | |
fp1 = fopen(argv[1], "rb"); | |
//Check that file is opened | |
if (fp1 == NULL){ | |
fprintf(stdout,"The Input File Was Not Found.\n"); | |
return EXIT_FAILURE; | |
} | |
//Open output file for writeing. | |
fp2 = fopen(argv[2], "wb"); | |
//Check that output file was created. | |
if (!fp2){ | |
fprintf(stdout,"Cannot Write To Output File.\n"); | |
_fcloseall(); | |
return EXIT_FAILURE; | |
} | |
//Read input file data | |
srand(PasswordKey(argv[3])); | |
while (!feof(fp1)){ | |
//Get char from input | |
c = getc(fp1); | |
if (!feof(fp1)){ | |
//Get random value from key | |
key = rand() % 255; | |
//Xor key with current char | |
key ^= c; | |
//Write char to output file. | |
fputc((char)key, fp2); | |
} | |
} | |
//Close opened files | |
_fcloseall(); | |
return EXIT_SUCCESS; | |
} |
Thanks Rick for the info I now had time to update the changes you said I also done a few other minor tweaks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would use
fcloseall()
instead offclose()
. How you probably could guess by the name it closes all files in one Command. What I also would change is the return values.. instead of 1 or 0 I´d be usingEXIT_FAILURE
/EXIT_SUCCESS
, however this doesn´t change anything it´s just in my opinion a better way to do it. Last but not least, I´d also change all of thatprintf()
commands intofprintf()
, the only diffrence here is, that it´s much safer to work with and the first parameter is where the txt should be displayed on.Otherwise great job!