2016-03-01 97 views
1

我目前正試圖通過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; 
} 

考慮到控制檯輸入異或的問題,會出現什麼問題?

+2

'函數getline()'消耗''\ n''(換行)字符。你應該使用'std :: ifstream :: read()'函數讀取你的文件。 –

+0

在字符串中有'\ 0'是很好的,你只需要小心不要使用函數作爲字符串結束的標記。如果你只是在處理字符串和調用你的例子(使用'.c_str()'或'.data()'和'.length()'),你應該沒問題。 –

+0

πάντα-ῥεῖ是正確的,如果你只與'multiline'文件的問題,你應該尋找您的問題在線路末端的處理! –

回答

1

XOR可產生零個字符,這是由std::string

std::string提供重載到大多數功能,其允許用戶指定輸入的數據的大小解釋爲線端。它還允許您檢查存儲數據的大小。因此,std::string內的0值char是完全合理且可接受的。

因此,問題不在於std::string將空值視爲行尾,但可能是std::getline(),可能是這樣做的。

我看到你正在使用std::ostream::write()讓我看到你已經熟悉了用大小作爲參數。那麼爲什麼不使用std::istream::read()而不是std::getline()

因此,您可以在「塊」或文件,而不是需要治療的行分隔符作爲特殊情況的「塊」簡單地閱讀。