答案:
我必须创建一个单独的解密函数,使用"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;
}
}发布于 2013-09-26 16:32:20
由于加密数据不再是文本,您应该在打开I/O加密文件时使用"wb"和"rb"。
https://stackoverflow.com/questions/19033411
复制相似问题