[英]C++ - Read the bytes of any file into an unsigned char array
我有一個任務,我必須為 AES-128 加密實施 Rijndael 算法。 我有算法可操作,但我沒有正確的文件輸入/輸出。
賦值要求我們使用從命令行傳入的參數。 在這種情況下,參數將是用戶希望加密的特定文件的文件路徑。
我的問題是,我不知道如何讀取文件的字節並將這些字節存儲在數組中以供以后加密。
我曾嘗試使用 ifstream 和 ofstream 來打開、讀取、寫入和關閉文件,它適用於純文本文件。 但是,我需要應用程序將任何文件作為輸入。
當我嘗試使用 fstream 和 pdf 作為輸入的方法時,它會使我的程序崩潰。 所以,我現在需要學習如何獲取文件的字節,將它們存儲在 unsigned char 數組中以進行加密,然后將它們存儲在另一個文件中。 這個加密和存儲密文的過程需要以 16 個字節為間隔進行。
下面的實現是我第一次嘗試以二進制模式讀取文件,然后以二進制模式寫入另一個文件中讀取的任何內容。 output 可在十六進制閱讀器中讀取。
int main(int argc, char* argv[])
{
if (argc < 2)
{
cerr << "Use: " << argv[0] << " SOURCE_FILEPATH" << endl << "Ex. \"C\\Users\\Anthony\\Desktop\\test.txt\"\n";
return 1;
}
// Store the Command Line Parameter inside a string
// In this case, a filepath.
string src_fp = argv[1];
string dst_fp = src_fp.substr(0, src_fp.find('.', 0)) + ".enc";
// Open the filepaths in binary mode
ifstream srcF(src_fp, ios::in | ios::binary);
ofstream dstF(dst_fp, ios::out | ios::binary);
// Buffer to handle the input and output.
unsigned char fBuffer[16];
srcF.seekg(0, ios::beg);
while (!srcF.eof())
{
srcF >> fBuffer;
dstF << fBuffer << endl;
}
dstF.close();
srcF.close();
}
代碼實現未按預期工作。
任何有關如何解決我的困境的方向將不勝感激。
像你一樣,我真的很難找到一種方法將二進制文件讀入 C++ 中的字節數組,這將使 output 與我在十六進制編輯器中看到的相同十六進制值。 經過多次試驗和錯誤,這似乎是無需額外演員的最快方法。
如果沒有計數器,它會更快 go ,但有時你會得到寬字符。 要真正一次獲得一個字節,我還沒有找到更好的方法。
默認情況下,它將整個文件加載到 memory 中,但只打印前 1000 個字節。
string Filename = "BinaryFile.bin";
FILE* pFile;
pFile = fopen(Filename.c_str(), "rb");
fseek(pFile, 0L, SEEK_END);
size_t size = ftell(pFile);
fseek(pFile, 0L, SEEK_SET);
uint8_t* ByteArray;
ByteArray = new uint8_t[size];
if (pFile != NULL)
{
int counter = 0;
do {
ByteArray[counter] = fgetc(pFile);
counter++;
} while (counter <= size);
fclose(pFile);
}
for (size_t i = 0; i < 800; i++) {
printf("%02X ", ByteArray[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.