【问题标题】:Decrypting XOR-encrypted file aborts prematurely解密 XOR 加密文件过早中止
【发布时间】:2013-03-18 02:19:16
【问题描述】:

使用一个名为Encryptor的简单函子

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

我可以轻松地加密给定文件

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));

但是试图通过调用来恢复它

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));

仅部分起作用。以下是文件大小:

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

在这种情况下,该方法似乎只适用于第一个 2**12 字节,并且可能只适用于它的倍数(它可能是我的文件系统的块大小吗?)。 我为什么会出现这种行为,有什么解决方法?

【问题讨论】:

  • 显然,当我尝试重现此内容时不会发生这种情况。
  • @moooeeeeep:谁知道微软的 C++ 编译器与 gcc 或 clang 相比如何“优化”?我假设如果我将 { /*...*/ } 之间的两个用于加密/解密的块移动到自己的范围内,这样流将自动关闭,则不会发生此错误。

标签: c++ file encryption stl stream


【解决方案1】:

从您提供的源代码中,看起来输出流在您尝试从磁盘读回之前没有关闭。由于 ofstream 类中有一个输出缓冲区,因此您的数据可能仍在缓冲区中,因此未刷新到磁盘。在从磁盘读取之前关闭输出流应该可以解决问题。

【讨论】:

  • 这不能以当前形式回答问题,应该是评论。
  • @RichardJ.RossIII:它没有回答问题,但 Ale 是完全正确的!这确实是我没有得到正确输出的原因。
  • 好的!我将稍微编辑一下答案,使其更加清晰/明确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
相关资源
最近更新 更多