gpt4 book ai didi

C++异或加密截断文件

转载 作者:行者123 更新时间:2023-11-30 05:30:59 25 4
gpt4 key购买 nike

我目前正在尝试通过 XOR 实现文件加密。虽然很简单,但我对多行 文件的加密感到很吃力。
实际上,我的第一个问题是 XOR 可以产生零字符,这些字符被 std::string 解释为行结束,因此我的解决方案是:

std::string Encryption::encrypt_string(const std::string& text) 
{ //encrypting string

std::string result = text;

int j = 0;
for(int i = 0; i < result.length(); i++)
{
result[i] = 1 + (result[i] ^ code[j]);
assert(result[i] != 0);

j++;
if(j == code.length())
j = 0;
}
return result;
}

std::string Encryption::decrypt_string(const std::string& text)
{ // decrypting string
std::string result = text;
int j = 0;
for(int i = 0; i < result.length(); i++)
{
result[i] = (result[i] - 1) ^ code[j];
assert(result[i] != 0);

j++;
if(j == code.length())
j = 0;
}

return result;
}

不是很整洁,但对于第一次尝试来说还不错。但是当尝试加密文本文件时,我了解到,根据加密 key ,我的输出文件会在随机位置被截断。我最好的想法是,\n 处理不正确,因为来自键盘的字符串(即使使用 \n)不会破坏代码。

bool Encryption::crypt(const std::string& input_filename, const std::string& output_filename, bool encrypt)          
{ //My file function
std::fstream finput, foutput;
finput.open(input_filename, std::fstream::in);
foutput.open(output_filename, std::fstream::out);

if (finput.is_open() && foutput.is_open())
{
std::string str;
while (!finput.eof())
{
std::getline(finput, str);
if (encrypt)
str.append("\n");
std::string encrypted = encrypt ? encrypt_string(str) : decrypt_string(str);
foutput.write(encrypted.c_str(), str.length());
}

finput.close();
foutput.close();

return true;
}

return false;
}

考虑到控制台输入的异或运算正常,可能是什么问题?

最佳答案

XOR can produce zero chars, which are interpreted as line-end by std::string

std::string 为大多数功能提供重载,允许您指定输入数据的大小。它还允许您检查存储数据的大小。因此,std::string 中的 0 值 char 是完全合理和可接受的。

因此,问题不在于 std::string 将空值视为行尾,而在于 std::getline() 可能正在这样做。

我看到您正在使用 std::ostream::write() 所以我看到您已经熟悉使用大小作为参数。那么,为什么不也使用 std::istream::read() 而不是 std::getline()

因此,您可以简单地读入文件的“ block ”或“ block ”,而不需要将行分隔符视为一种特殊情况。

关于C++异或加密截断文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35729736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com