0

So, I'm trying to implement a XOR encryption as follows :

string XOR(char *data, char *key) {
    for (int i = 0; i != sizeof(data); i++)
    {
        data[i] ^= key[i % sizeof(*key)];
    }
    cout << sizeof(data) << "\n";
    return data;
}

This is the function that will take as input data and key The important thing here is that for each character in the array data, a XOR operation is made with the key, hence the for loop : for (int i = 0; i != sizeof(data); i++)...

The problem arises with sizeof(data) which returns 4 or my expcted output would be 27 (26 letters in the alphabet + the null terminator (I think)).

The program outputs this :

4
 #"%efghijklmnopqrstuvwxyz

Only the first 4 letters are processed correctly.

What is strange is that sizeof(str) returns 27 which is corect so why sizeof(data) returns 4 ?

So what do I need to change in the parameters of the fucntion XOR ?

Here is the entire code :

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

string XOR(char *data, char *key) {
    for (int i = 0; i < sizeof(data) + 1; i++)
    {
        data[i] ^= key[i % sizeof(*key)];
    }
    cout << sizeof(data);
    return data;
}

int main()
{
    char clef[] = "A";
    char str[] = "abcdefghijklmnopqrstuvwxyz";

    cout << XOR(str, clef) << "\n";
}
Polymood
  • 397
  • 3
  • 14
  • Another duplicate: [Why is sizeof(str) is equal to 8 , when it should be equal to strlen(str)+1 ... (because of extra null char)?](https://stackoverflow.com/questions/62944380/why-is-sizeofstr-is-equal-to-8-when-it-should-be-equal-to-strlenstr1) (the third hit when I searched this site for `[c++] sizeof strlen`) – JaMiT Nov 07 '21 at 18:18

1 Answers1

0

The fix is simple : instead of using sizeof(), use strlen() like so :

string XOR(char *data, char *key) {
    for (int i = 0; i != strlen(data); i++)
    {
        data[i] ^= key[i % strlen(key)];
    }
    cout << strlen(data) << "\n";
    return data;
}

Note that in the following case :

char str[] = "abcdefghijklmnopqrstuvwxyz"; , strlen(str) will return 26, not 27 as it would have been the case using sizeof(str)

Polymood
  • 397
  • 3
  • 14
  • Even worse, if you apply `sizeof` to a pointer (e.g. `data`) it will give you the size of the pointer, typically 4 or 8. – Lindydancer Nov 07 '21 at 18:12