c++ - 如何在 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
解决方案
我认为你应该先测试你的加密/解密,而不需要所有的文件。
当心完全没有测试过的代码
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,则您的编码/解码工作,否则您可以专注于该部分,否则您需要首先开始调试。
推荐阅读
- python - 仅在代码中输出 True 或 False(循环)
- r - 如何在同一管道中正确删除 NA 并将字符串转换为标题?
- python - Dask-ml LabelEncoder.fit_tranform() throw AttributeError: 'bool' object has no attribute 'astype'
- bootstrap-4 - 移动设备和台式机上的引导卡大小不同
- c# - 在游戏中正确使用 continue 和 break 语句
- python - 有没有办法用python模仿声音输入?
- iis - Windows 10 上的 BITS IIS 服务器扩展
- maven - 用maven创建一个独立的jar,不用组装插件
- xml - 使用 Powershell 在 XML 文件中添加行
- mysql - MySQL间隙锁定