Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrypting XOR-encrypted file aborts prematurely

Using a simple functor called Encryptor

struct Encryptor {
    char m_bKey;
    Encryptor(char bKey) : m_bKey(bKey) {}
    char operator()(char bInput) {
        return bInput ^ m_bKey++;
    }
};

I can encrypt a given file easily with

std::ifstream input("in.plain.txt", std::ios::binary);
std::ofstream output("out.encrypted.txt", std::ios::binary);
std::transform(
    std::istreambuf_iterator<char>(input),
    std::istreambuf_iterator<char>(),
    std::ostreambuf_iterator<char>(output),
    Encryptor(0x2a));

however trying to revert this by calling

std::ifstream input2("out.encrypted.txt", std::ios::binary);
std::ofstream output2("out.decrypted.txt", std::ios::binary);
std::transform(
    std::istreambuf_iterator<char>(input2),
    std::istreambuf_iterator<char>(),
    std::ostreambuf_iterator<char>(output2),
    Encryptor(0x2a));

does only work partly. Here are the file sizes:

in.plain.txt:      7,700 bytes
out.encrypted.txt: 7,700 bytes
out.decrypted.txt: 4,096 bytes

In this case it seems, that the method only work for the first 2**12 bytes and probably only for multiples of it (could it be my blocksize of the filesystem?). Why do I have this behavior and what is a workaround for this?

like image 285
Christian Ivicevic Avatar asked Oct 05 '22 14:10

Christian Ivicevic


1 Answers

Form the source code you give, it looks like the output stream is not closed before you try to read it back from the disk. As there is an output buffer in the ofstream class, it might be that your data is still in the buffer and thus not flushed to disk. Closing the output stream before reading it from disk should solve the problem.

like image 193
Ale Avatar answered Oct 13 '22 11:10

Ale