Search code examples
cencryptionvisual-studio-2017xor

XOR-Encryption works on Code blocks not on Visual Studio 2017


so I would like to encrypt my data when write into .txt file so I choose XOR-Encryption from this code: Github So when I run in code blocks it runs and shows this result:

Encrypted: :=.43*-:8m2$.a
Decrypted:kylewbanks.com0

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.

But When I start use Visual Studio 2017 it shows this error:

Error (active)  E0059   function call is not allowed in a constant expression   

Which means I cant put variable when declaring an array, so is there any method for my encryption to work in VS2017. I think the problems is when declare the variable using constant, anyway to force it or other encryption method that is easy to use, I wont need to be secure just to prevent plain text in file. Anyway this is the only code:

#include <stdio.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array

    int i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
}

int main () {
    char baseStr[] = "kylewbanks.com";

    char encrypted[strlen(baseStr)];
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char decrypted[strlen(baseStr)];
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);
}

Solution

  • MSVC does not support Variable Length Arrays. One way round is to allocate the memory.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void encryptDecrypt(char *input, char *output) {
        char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array
        size_t i;
        for(i = 0; i < strlen(input); i++) {
            output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
        }
        output[i] = '\0';               // terminate
    }
    
    int main () {
        char baseStr[] = "kylewbanks.com";
        size_t len = strlen(baseStr) + 1;
    
        char *encrypted = malloc(len);
        if(encrypted == NULL) {
            // error handling
        }
        encryptDecrypt(baseStr, encrypted);
        printf("Encrypted:%s\n", encrypted);
    
        char *decrypted = malloc(len);
        if(decrypted == NULL) {
            // error handling
        }
        encryptDecrypt(encrypted, decrypted);
        printf("Decrypted:%s\n", decrypted);
    
        free(decrypted);
        free(encrypted);
    }
    

    Please note that an extra byte is needed for the string terminator - and the string should be terminated.