【问题标题】:How to decrypt file using XOR in c++?如何在 C++ 中使用 XOR 解密文件?
【发布时间】:2020-05-12 22:08:33
【问题描述】:

我正在使用 C++ 学习密码学,所以我开始使用非常简单的 XOR,我想打开文件 0x1.txt 并使用 3 个密钥的 XOR 对其进行加密,然后创建一个名为 0x2.txt 的新文件并将加密的数据放入其中,解密后将其内容放入0x3.txt:

encrpyt -> 0x1.txt -->将加密数据放入0x2.txt;解密 0x2.txt --> 将解密后的数据放入0x3.txt

这是我的代码:

加密代码:

LPVOID Crypt(HANDLE hFile, DWORD dwFileSize) {
    // allocate buffer for file contents
    LPVOID lpFileBytes = malloc(dwFileSize);
    // read the file into the buffer
    ReadFile(hFile, lpFileBytes, dwFileSize, NULL, NULL);

    // apply XOR encryption
    int i;
    char key[3] = {'*', '~', '#'};
    for (i = 0; i < dwFileSize; i++) {
        *((LPBYTE)lpFileBytes + i) ^= key[i % sizeof(key)];
    }

    return lpFileBytes;
}

调用函数加密文件:

HANDLE hFile = CreateFile("0x1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        // get file size
        DWORD dwFileSize = GetFileSize(hFile, NULL);
        CloseHandle(hFile);
        // crypt and get crypted bytes
        LPVOID lpFileBytes = Crypt(hFile, dwFileSize);

然后将加密后的数据放入 0x2.txt 中:

HANDLE hCryptedFile = CreateFile("0x2.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

        // write to crypted file
        WriteFile(hCryptedFile, lpFileBytes, dwFileSize, NULL, NULL);

现在我想解密我制作的 0x2.txt 文件的内容:

HANDLE hFile = CreateFile("0x2.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        // get file size
        DWORD dwFileSize = GetFileSize(hFile, NULL);

        // decrypt and obtain decrypted bytes
        LPVOID lpFileBytes = Crypt(hFile, dwFileSize);
        CloseHandle(hFile);

创建文件0x3.txt:

HANDLE hTempFile = CreateFile("0x3.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        // write to temporary file
        WriteFile(hTempFile, lpFileBytes, dwFileSize, NULL, NULL);
        // clean up
        CloseHandle(hTempFile);
        free(lpFileBytes);

但是文件,它加密更多,而不是解密!。那么它的问题是什么? 这是我的完整代码:

https://pastebin.com/6WZX5J1K

【问题讨论】:

标签: c++ encryption xor


【解决方案1】:

我认为你应该先测试你的加密/解密,而不是所有文件。

注意完全没有测试过的代码

void Encrypt( std::string& txt) {
  // apply XOR encryption
  int i;
  char key[3] = {'*', '~', '#'};
  for (i = 0; i < txt.length(); i++) {
    txt[i] ^= key[i % sizeof(key)];
  }
}

bool Test() {
  std::string org { "123" };
  std::string encrypted = org;
  Encrypt(encrypted, encrypted.length());
  std::string decrypted = encrypted;
  Encrypt(decrypted, decrypted.length());
  // std::cout << org << " " << encrypted << " " << decrypted << std::endl;
  return org == decrypted;
}

如果 Test 返回 true,则您的编码/解码工作,否则您可以专注于该部分,否则您需要首先开始调试。

【讨论】:

  • 非常感谢,我已经测试了我的加密并且它有效,我通过查看 0x2.txt 的内容对此非常满意,它是加密的。但在 0x3.txt 中解密的整个问题,它包含加密数据,而不是解密。这是我的完整代码:pastebin.com/6WZX5J1K,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2015-12-16
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
相关资源
最近更新 更多