Search code examples
cfile-handlingxor

XOR Cipher using native C


I am practicing my C file handling knowledge by coding a program that encrypts-decrypts a file by a given path. The problem is that my program is encrypting the file but never decrypt it.

I will share below a snippet of code of my program hopefully someone can figure out what's wrong with it.

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include<stdint.h>
#include<stddef.h>
void flush_n(){
    int c = 0;
    while((c = getchar())!= '\n' && c!= EOF);
}
int main(void){
    char path[281];
    puts("Please enter the path of the file you want to encrypt\\decrypt:");
    scanf("%280s",path);
    FILE*fp = fopen(path,"rb+");
    if(fp==NULL){
        fprintf(stderr,"Unable to open the file!\n");
        Sleep(2000);
        return EXIT_FAILURE;
    }
    fseek(fp,0,SEEK_END);
    size_t size = ftell(fp);
    rewind(fp);
    char*buff = (char*)malloc(size*sizeof(char));
    if(buff==NULL){
        fprintf(stderr,"Unable to allocate memory!\n");
        Sleep(2000);
        return EXIT_FAILURE;
    }
    const uint32_t KEY = 0x4FC5D4B;
    for(size_t i = 0;i < size; i++)
        buff[i] ^= (char)KEY;
    fwrite(buff,size,sizeof(char),fp);
    fclose(fp);
    free(buff);
    flush_n();
    MessageBoxA(NULL,"The file has been successfully encrypted\\decrypted!","DONE!",MB_OK|MB_ICONINFORMATION);
    puts("Please press any key to close this window...");
    getchar();
    return EXIT_SUCCESS;
}

Solution

  • You allocate memory for the file contents, and you XOR the contents of that memory with (a small part of) the KEY, and then you write the contents of the buffer to the file, overwriting its previous contents. But nowhere do you actually read anything from the file.

    You're just ciphering the contents of the uninitialized buffer, so the output will just be random bytes.

    Between the malloc and the ciphering loop, you need to call fread to actually read the data from the file into the buffer.