XOR Encryption in C with key

105 Views Asked by At

I am trying a simple XOR encryption in C/C++ for Windows. To achieve this I am using a key "SECRETKEY" and a character array "payload". If at some point the value of current key value is equal to that of the current payload value, then the result is 0x00, therefore terminating the string. What's a common workaround?

const char key[] = "tSECRETKEY";


void XORCipher(char * payload) {
    
    // Key pointer
    int j = 0;

    int a = sizeof(payload);

    for (int i = 0; i < strlen(payload); i++) {
        *(payload + i) = *(payload + i) ^ key[j];
        j++;

        if (j == sizeof(key))
            j = 0;
    }

}

int main()
{
    char payload[] = "test";

    XORCipher(payload);
    XORCipher(payload);

    printf("%s\n", payload);

    return 0;
}

Result is empty, as expected.

1

There are 1 best solutions below

1
Eric Postpischil On

If at some point the value of current key value is equal to that of the current payload value, then the result is 0x00, therefore terminating the string. What's a common workaround?

Measure the length of the plaintext string. Let L be that length. Encrypt the string. Write L bytes of the ciphertext to output. In other words, do not use functions that use a null character to terminate a string; use code and functions that write a definite specified number of characters. You can use fwrite(ciphertext, 1, L, stdout) for this.

Note that typical “terminal” software has a number of characters that do not print recognizable distinct characters. The null character is one such, and there are others. So merely writing raw characters to a terminal is not a useful way to convey ciphertext. It might work for writing to a file. For a terminal, you need some other way to represent ciphertext, such as converting it to hexadecimal.

If you want the output to convey the length of the ciphertext, you must also write that or indicate it in some way.