答:XOR加密失敗
我不得不做出解密一個單獨的功能使用「RB」打開加密文件,然後使用「WB」在加密函數寫的加密數據到文件。
我的Xor加密出了問題。當加密文件中的數據時,加密工作正常,但當我嘗試解密時,加密失敗。問題是fgetc
函數只讀取第一行和第二行,並且無法解密第二行的50%。
實施例:
正常:
This is a text, This is a text
This is a text, This is a text
加密:
a¦_ÖÞ`×ûù‡ûÛ(‹Pñ»FŒ§U®7!¼ªãŸ<çϱ\Î8ðs6Öã`GÒFAªÓV/Ç1t
解密的:
This is a text, This is a text
This is a text, ±Åãl«åé»–o„ F
我檢查的代碼具有斷點,看到的問題是,fgetc
停止讀取第二行後的文件,但我不知道爲什麼。也許我的算法有問題。
代碼:
int encrypt_file(const char *filename, const char *key)
{
int i = 0;
size_t key_len = strlen(key);
size_t key_count = 0;
size_t num_bytes = 0;
int *data = NULL;
int byte = 0;
FILE *file;
fopen_s(&file, filename, "r");
if (file != NULL)
{
// get file size/number of bytes
fseek(file, 0L, SEEK_END);
num_bytes = ftell(file);
fseek(file, 0L, SEEK_SET);
// allocate enough memory for the data
data = (int*)malloc(sizeof(int) *num_bytes);
// stores the data from the file in the array
while ((data[i++] = fgetc(file)) != EOF);
// encrypt the data
for (i = 0; i < num_bytes; i++) {
data[i] = data[i]^key[key_count++];
if (key_count == key_len) {
key_count = 0;
}
}
fclose(file);
fopen_s(&file, filename, "w");
// write the data from the array to the same file
for (i = 0; i < num_bytes; i++) {
fputc(data[i], file);
}
fclose(file);
return 0;
}
else
{
return 1;
}
}
打開輸出文件時,應該使用''wb「'而不是''w」',因爲它不再是文本。 – timrau
@timra正確使用「wb」。另外,請確保使用「rb」打開解密文件。 – chux