Skip to content

Instantly share code, notes, and snippets.

@qwe321qwe321qwe321
Created February 12, 2020 00:42
Show Gist options
  • Save qwe321qwe321qwe321/af05fd33899e3cfff38e9330d437f36a to your computer and use it in GitHub Desktop.
Save qwe321qwe321qwe321/af05fd33899e3cfff38e9330d437f36a to your computer and use it in GitHub Desktop.
XOR two files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MAX_KEY_BYTE 65536
int binSize(FILE *fp) {
fseek(fp, 0, SEEK_END); // seek to end of file
int size = ftell(fp); // get current file pointer
fseek(fp, 0, SEEK_SET); // seek back to beginning of file
return size;
}
int xor_file(const char *cryptoFile, const char *keyFile, const char *outfile) {
FILE *fpCrypto, *fpKey, *fpo;
if ((fpCrypto = fopen(cryptoFile, "rb")) == NULL) {
fprintf(stderr, "Cannot open crpyto file %s: %s\n", cryptoFile, strerror(errno));
return 1;
}
if ((fpKey = fopen(keyFile, "rb")) == NULL) {
fprintf(stderr, "Cannot open key file %s: %s\n", keyFile, strerror(errno));
fclose(fpCrypto);
return 1;
}
if ((fpo = fopen(outfile, "wb")) == NULL) {
fprintf(stderr, "Cannot open output file %s: %s\n", outfile, strerror(errno));
fclose(fpCrypto);
fclose(fpKey);
return 2;
}
int keySize = binSize(fpKey);
char *keyBuffer = (char*)malloc(sizeof(char) * keySize);
if (fread (keyBuffer, 1, keySize, fpKey) != keySize) {
fprintf(stderr, "Key file is broken: %s\n", strerror(errno));
}
int cryptoSize = binSize(fpCrypto);
char *cryptoBuffer = (char*)malloc(sizeof(char) * cryptoSize);
if (fread (cryptoBuffer, 1, cryptoSize, fpCrypto) != cryptoSize) {
fprintf(stderr, "Crypto file is broken: %s\n", strerror(errno));
}
for (int i = 0; i < cryptoSize; i++) {
cryptoBuffer[i] ^= keyBuffer[i % keySize];
}
fwrite(cryptoBuffer, sizeof(char), cryptoSize, fpo);
// Close
fclose(fpCrypto);
fclose(fpKey);
fclose(fpo);
free(keyBuffer);
free(cryptoBuffer);
return 0;
}
int main(int argc, char *argv[]) {
if (argc == 4) {
xor_file(argv[1], argv[2], argv[3]);
} else {
fprintf(stderr, "usage:key.exe <crypto_file> <key_file> <output_file>\n");
}
//getch(); // avoid the need for this by running your program in the terminal
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment