2016-03-01 90 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()

因此,您可以在“块”或文件,而不是需要治疗的行分隔符作为特殊情况的“块”简单地阅读。