首页 > 解决方案 > 如何在 C++ 中使用 XOR 解密文件?

问题描述

我正在使用 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++encryptionxor

解决方案


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

当心完全没有测试过的代码

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,则您的编码/解码工作,否则您可以专注于该部分,否则您需要首先开始调试。


推荐阅读