所以我试图在 C 中制作一个文件加密程序(顺便说一下,我对 C 有点陌生)所以我写了这个简单的 XOR 文件加密代码:
#include <stdio.h>
#include <string.h>
int main()
{
char fileName1[35] = {'\0'}; //Name of original file
char fileName2[35] = {'\0'}; //Name of encrypted file
char keyString[20] = {'\0'}; //Key determines result encryption
FILE* originalFile; //File to be encrypted
FILE* cryptedFile; //The encrypted file
int c; //byte read from original file
printf("Enter file location followed by name of the file you want to encrypt: ");
scanf("%s", fileName1);
printf("Enter file location followed by name of the encrypted file: ");
scanf("%s", fileName2);
printf("Enter your key (Encryption changes based on Key): ");
scanf("%s", keyString);
originalFile = fopen(fileName1, "rb"); //rb to read file bytes
cryptedFile = fopen(fileName2, "wb"); //wb to write bytes to file
if(originalFile != NULL && cryptedFile != NULL){
while( (c = getc(originalFile)) != EOF ){
int x;
for(x=0; x<strlen(keyString); x++){
c ^= keyString[x];
putc(c, cryptedFile);
}
}
fclose(originalFile);
fclose(cryptedFile);
}
return 0;
}
所以为了测试这个程序,我创建了一个名为 file1.txt 的文件并运行加密程序,将第二个文件作为 file2.txt 并将密钥作为secret。然后我再次运行该程序,但这次是在加密的 file2.txt 上并创建了一个具有相同密钥secret的 file3.txt 。由于它是相同的密钥,因此 file3.txt 应该与 file1.txt 相同,但 file3.txt 中包含随机内容。那么我做错了什么?