我從沒想過我必須求助于 SO 來解決這個問題。
好吧,為了獲得更多洞察力,我正在制作自己的加密程式。我不是想讓它變得更好或任何它只是一個個人專案。這個程式正在做的是它翻轉字符的每個位元組中的某些位,使其不可讀。
但是,每次我運行程式并解密時,我都會在輸出中得到奇怪的字符。這些字符似乎與以下行數相匹配:
^^ 我要加密的文本
^^ 加密后。(很多文字被剪掉了)

^^ 解密后。有 10 個空字符對應于換行符的數量。似乎還有另一個奇怪的“ ”字符。這些位元組來自哪里?
我已經嘗試了很多東西。如果有人需要,這是我的代碼(它是使用默認標志編譯的):
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#define ENCRYPTFILE "Encrypted.oskar"
typedef unsigned char BYTE;
char saltFunc(BYTE salt, char chr) {
for(int i = 0; i < 8; i ) {
if((salt >> i) & 1U) {
chr ^= 1UL << i;
}
}
return chr;
}
int main () {
std::ofstream encryptFile(ENCRYPTFILE, std::ifstream::in);
std::ifstream inputFile(ENCRYPTFILE, std::ifstream::in);
unsigned int length;
unsigned int lineLength;
BYTE salt = 0b00000001;
std::string line;
std::cin.unsetf(std::ios::dec);
std::cin.unsetf(std::ios::hex);
std::cin.unsetf(std::ios::oct);
//std::cout << "input salt in hex with a prefix 0x so for example. 0xA2" << std::endl;
//std::cin >> std::hex >> salt;
inputFile.seekg(0, inputFile.end);
length = inputFile.tellg();
inputFile.seekg(0, inputFile.beg);
std::cout << lineLength << std::endl;
char* fileBuffer = new char[length];
char* encryptFileBuffer = new char[length];
memset(fileBuffer, 0, length);
memset(encryptFileBuffer, 0, length);
while (inputFile.good()) { // just get file length in bytes.
static int i = 0;
fileBuffer[i] = inputFile.get();
i ;
}
while (std::getline(inputFile, line))
lineLength;
inputFile.clear();
encryptFile.clear();
std::cout << "file size: " << length << std::endl;
for(int i = 0; i < length; i ) {
encryptFileBuffer[i] = saltFunc(salt, fileBuffer[i]);
encryptFile << encryptFileBuffer[i];
}
inputFile.close();
encryptFile.close();
delete[] encryptFileBuffer;
delete[] fileBuffer;
return 0;
}
uj5u.com熱心網友回復:
問題是您正在以位元組為單位測量檔案的長度,對于文本檔案,它與以字符為單位的長度不同。但是您隨后將其作為字符讀取,因此您最終會讀取太多字符,然后在輸出檔案中結束后寫入額外的垃圾。
由于每行多出一個字符,因此很可能您在 Windows 上運行,其中行結束字符是檔案中的兩個位元組。這就是您看到的額外錯誤長度的來源。
對于加密/解密,您可能想要做的是以二進制模式讀取和寫入檔案,因此您正在讀取和寫入bytes而不是characters。您可以通過std::ios::binary在打開檔案時添加標志來做到這一點:
std::ofstream encryptFile(ENCRYPTFILE, std::ifstream::in | std::ios::binary);
std::ifstream inputFile(ENCRYPTFILE, std::ifstream::in | std::ios::binary);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413566.html
標籤:
