C ++ XOR加密 - 解密问题

时间:2015-12-12 19:22:21

标签: c++ encryption cryptography xor

我在stephan-brumme网站上关于XOR加密的教程(遗憾的是我不能包含URL因为我没有足够的声誉)。我想要做的是:阅读example.txt文件的内容并解密它包含的文本。例如,这是example.txt的内容:

<!DOCTYPE html5>

当使用密码&#34;密码&#34;解密时应该回来&#34;你好&#34;。这是我得到的代码:

\xe7\xfb\xe0\xe0\xe7

这是运行应用程序的结果: click for image

如您所见,解密未成功。现在,如果我这样做它不会读取.txt,而是直接解密文本,如下所示:

#include <string>
#include <iostream>
#include <fstream>

using namespace std;

std::string decode(const std::string& input)
{
  const size_t passwordLength = 9;
  static const char password[passwordLength] = "password";
  std::string result = input;
  for (size_t i = 0; i < input.length(); i++)
    result[i] ^= ~password[i % passwordLength];
  return result;
}

int main(int argc, char* argv[])
{
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << decode(line);
    }
    myfile.close();
  }

  return 0;
}

完美无缺: click for image

我在这里做错了什么?

非常感谢提前! :)

2 个答案:

答案 0 :(得分:1)

我打赌example.txt包含字符'\','x','e','7'等等。您必须阅读这些字符,处理所有反斜杠转义符,然后然后提要它解码。

\ xe7是用十六进制值E7表示单个字符的常用方法。 (这很可能是单个字符'ç',具体取决于你的字符集)。如果你想存储(加密)可读文本,我建议删除\ x,并让文件包含像“e7fbe0e0e7”这样的行。然后   - 将每一行读成一个字符串。   - 将每对字符从十六进制数转换为整数,并将结果存储在char中。   - 将该字符串存储在字符串中。   - 然后xor解密字符串。

或者,确保文件包含您需要的实际二进制字符。

还要注意您正在使用密码的终止空字节进行异或。你的意思是这样做吗?

答案 1 :(得分:1)

相同字符的字符XOR为零,因此结果可能包括零。 std::string不喜欢这样,因为零终止字符串。

您还可以使用std::vector<char>代替std::string进行实际编码/解码。您必须更改decode函数才能处理vector<char>

以二进制文件读/写文件。

修改:仅使用std::stringstd::string decode(const std::string& input)

int main()
{
    std::string line = "hello";

    {
        line = decode(line);
        std::ofstream myfile("example.txt", std::ios::binary);
        myfile.write(line.data(), line.size());

        //Edit 2 *************
        //std::cout << std::hex;
        //for (char c : line)
        //  std::cout << "\\x" << (0xff & c);
        //*************
        //This will make sure width is always 2
        //For example, it will print "\x01\x02" instead of "\x1\x2"
        std::cout << std::hex << std::setfill('0');
        for (char c : line)
            std::cout << "\\x" << std::setw(2) << (0xff & c);
        std::cout << std::endl;
    }

    {
        std::ifstream myfile("example.txt", std::ios::binary | std::ios::ate);
        int filesize = (int)myfile.tellg();
        line.resize(filesize);
        myfile.seekg(0);
        myfile.read(&line[0], filesize);
        line = decode(line);
        std::cout << line << std::endl;
    }

    return 0;
}
相关问题