我目前正试图通过XOR来实现文件加密。虽然简单,但是,我努力加密多行文件。
其实,我的第一个问题是,XOR可以产生零个字符,这是由std::string
解释为线端,因此我的解决办法是:C++ XOR加密截断文件
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;
}
不齐,但罚款的第一次尝试。但是,当试图隐藏文本文件时,我明白,根据加密密钥,我的输出文件会在随机位置被截断。我最好的想法是,这\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;
}
考虑到控制台输入异或的问题,会出现什么问题?
'函数getline()'消耗''\ n''(换行)字符。你应该使用'std :: ifstream :: read()'函数读取你的文件。 –
在字符串中有'\ 0'是很好的,你只需要小心不要使用函数作为字符串结束的标记。如果你只是在处理字符串和调用你的例子(使用'.c_str()'或'.data()'和'.length()'),你应该没问题。 –
πάντα-ῥεῖ是正确的,如果你只与'multiline'文件的问题,你应该寻找您的问题在线路末端的处理! –