FILE* readFile = fopen("readFile", "rb");
uint32_t b[2]; // buffer
uint32_t k[4] = { ... the key ...};
FILE* writeFile = fopen("writeFile", "wb");
while(we haven't reached the end of readFile) {
int read = 0;
while((read = fread(b, 4, 2, readFile)) > 0) {
doEncryption(b, k);
fprintf(writeFile, "%d", b[0]);
fprintf(writeFile, "%d", b[1]);
}
}
我正在尝试使用需要128位密钥和64位数据块的算法来加密数据。因此,我要尝试执行的操作是读取文件以加密并使用128位密钥,然后一次遍历文件64位并对其进行加密。当我加密它们时,我将它们写出一个文件,以后可以解密。问题是我不确定如何一次读取一个文件中的64位,然后写出相同的64位。我已经给了它第一遍,但它似乎没有正确加密。我是否在这里缺少一些基本的C编码步骤,即读取8个字节或写入8个字节?我有点新手,认为我的问题可能是如何读入
buffer或如何写至writeFile。任何帮助都会很棒,谢谢!
srcFile
读取8个字符到数组(char buf[9]
)。然后,通过在末尾添加buf[9]
字符,将数组'\0'
转换为字符串数组。然后,您可以根据需要使用该字符串。之后,将该字符串数组写入destfile
。该循环运行直到满足EOF
。#include <stdio.h>
#include <stdlib.h>
void main()
{
char srcFileName[25] = "file.txt";
char destFileName[25] = "destFile.txt";
FILE *srcFile;
FILE *destFile;
//printf("Enter name of a file you wish to encrypt\n");
//gets(fileName);
//printf("Enter name of a destination file\n");
//gets(fileName);
srcFile = fopen(srcFileName, "r");
destFile = fopen(destFileName, "w+");
if (srcFile == NULL || destFile == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int cntr = 0;
char ch;
char buf[9];
while(ch = fgetc(srcFile)) //Loop reads srcFile char by char
{
if (ch == EOF) // Looking for EndOfFile
{
buf[cntr] = '\0'; // Adding '\0' after last character
//encrypt(buf); // Encryption goes here
fputs(/*orMaybeEncrypt(*/buf/*)*/, fdest); // Or here; storing
// string to destFile
break; // Exit loop
}
if (cntr == 7) // checking for eighth caracter to be stored
{
buf[cntr]=ch; // adding eighth caracter to to buf[]
buf[8] = '\0'; // Adding '\0' to buf[] after eighth character
cntr=0; // zeroing counter
//encrypt(buf); // Encryption goes here
fputs(/*orMaybeEncrypt(*/buf/*)*/, destFile); // Or here; storing
// string to destFile
continue; // next iteration of loop
}
buf[cntr]=ch; // adding eighth caracter to to buf[]
cntr++; // counting passes
}
fclose(srcFile); // closing files
fclose(destFile); // closing files
}