我目前正試圖通過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'文件的問題,你應該尋找您的問題在線路末端的處理! –