jeudi 20 avril 2017

Bitwise XOR operation on UTF-8 string gives non UTF-8 output

I've built a basic XOR encryption program, which encrypts a .txt file using a key. It works fine, but I'd like for the file to only contain UTF-8 characters even after encryption. At the moment, I get output like this when viewed in a text editor:

1GCh!/39hpj1GCCh
hpj1GjjCCCh!/3hpj~yGCC7fGGCChhpj1GjjCCCh!/3hpj~xGCC7fGGCChhpj1GjjCCCh!/3hpj~{GCC7fGGCChhpj1GjjCCCh!/3hpjyrGCC7fGGCChhpj1GjjCCCh!/3hpjyGCC7fGGCChhpj1GjjCCCh!/3hpjy|GCC7fGGCCh
hpj1GjjCCCh!/3hpjy}GCC7fGGCCh
hpj1GjjCCCh!/3hpj~zGCC7fGGCChhpj1GjjCCCh!/3hpjysGCC7fGGCChhpj1GjjCCCh!/3hpj{~GCC7fGGCChhpj1GjjCCCh!/3hpj{GCC7fGGCCh
hpj1GjjCCCh!/3hpj{|GCC7fGGCChhpj1GjjCCCh!/3hpj{}GCC7fGGCChhpj1GjjCCCh!/3hpjh=hGCC7fGGCChhpj1GjjCCCh!/3hpjh+hGCC7fGGCChhpj1GjjCCCh!/3hpjh9hGCC7fGGCCh
hpj1GjjCCCh!/3hpjh.hGCC7GC7G7G

There are many artifacts here that I think are the result of non-UTF characters.

Is it possible to perform a bitwise XOR operation to yield UTF characters only?

For reference, here is my crypt function:

static std::string XORCrypt(std::string key, std::string data) {
    for (size_t i = 0; i != data.size(); i++) {
        data[i] ^= key[i % key.size()];
    }
    return data;
}

Aucun commentaire:

Enregistrer un commentaire