【发布时间】:2013-09-26 16:14:52
【问题描述】:
答案:
我必须制作一个单独的解密函数,使用 "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",因为它不再是文本了。 -
@timra 关于使用“wb”是正确的。另外,请确保您的解密文件是使用“rb”打开的。
标签: c encryption xor