【发布时间】: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