简体   繁体   English

用c加密和解密文件

[英]Encryption & Decryption a File in c

Here I have a simple code for Encryption & Decryption a File in C as below, 这里有一个简单的代码,用于在C中加密和解密文件,如下所示,

#include <stdio.h>
int Encrypt(char * FILENAME, char * NEW_FILENAME)    
{
    FILE *inFile;   //Declare inFile
    FILE *outFile;  //Declare outFile
    char Byte;
    char newByte;
    int n;
    int i=0;

    inFile = fopen(FILENAME,"rb");
    outFile = fopen(NEW_FILENAME, "w");

    if(inFile == NULL || outfile == NULL){
        printf("Error in opening file");
            return 1;
    } else {
        printf("\nFile Opened, Encrypting");
        while(1){
                while ( !feof( inFile ) ){
                    Byte=fgetc(inFile);
                    newByte=Byte+25;
                    fputc(newByte,outFile);
                } 
            printf("End of File");
            break;
        }
        fclose(inFile);
        fclose(outFile);
    }
}

int Decrypt (char *FILENAME, char *NEW_FILENAME)
{
    FILE *inFile; //Declare inFile
    FILE *outFile; //Declare outFile

    char Byte;
    char newByte;
    int i=0;

    inFile = fopen(FILENAME,"rb");
    outFile = fopen(NEW_FILENAME, "w");

    if(inFile == NULL || outfile == NULL){
        printf("Error in opening file");
        return 1;
    } else {
        printf("File Opened, Decrypting");
        while(1){
            printf(".");
            while ( !feof( inFile ) ){
                Byte=fgetc(inFile);
                newByte=Byte-25;
                fputc(newByte,outFile);
            } 
            printf("End of File");
            break;
        }
        fclose(inFile);
        fclose(outFile);
    }
}

int main()
{
    char encFile[200];
    char newencFile[200];
    char decFile[200];
    char newdecFile[200];

    int choice;

    printf("Enter 1 to Encrypt  / 2 to Decrypt");
    scanf("%d",&choice);

    switch(choice)
    {
    case 1:
        printf("Enter the Source Filename:  ");
        scanf("%s",encFile);
        printf("Enter the Destination Filename:   ");
        scanf("%s",newencFile);
        Encrypt(encFile, newencFile);
        break;
    case 2:
        printf("Enter the Source Filename:   ");
        scanf("%s",decFile);
        printf("Enter the Destination Filename:   ");
        scanf("%s",newdecFile);
        Decrypt(decFile, newdecFile);
        break;
    }
    return 0;
}

This code works but at the end of file it also contain "ÿæ" such characters so it can't open in default text-editor in linux & becomes useless to store private details. 该代码有效,但在文件末尾也包含"ÿæ"这样的字符,因此它无法在linux中的默认文本编辑器中打开,并且无法存储私有详细信息。 I want to get same to same stuff back in the discript file. 我想在discript文件中得到相同的东西。 Please help for the same, Thanks in advance. 请同样提供帮助,谢谢。

Your code is not correct. 您的代码不正确。 You probably expect that the encrypted file has the same size as the original file, but this is not the case. 您可能希望加密的文件具有与原始文件相同的大小,但是事实并非如此。 The faulty code is: 错误的代码是:

    while(1){
        printf(".");
        while ( !feof( inFile ) ){
            Byte=fgetc(inFile);
            newByte=Byte+25;
            fputc(newByte,outFile);
         } 
         printf("End of File");
         break;
    }

It must instead be: 相反,它必须是:

while ((Byte = fgetc(inFile)) != EOF) {
  newByte = Byte + 25;
  if (fputc(newByte, outFile) == EOF) {
    /* ERROR */
  }
}
printf("End of File\n");

Note that the printf statement ends with a newline character ( \\n ). 请注意, printf语句以换行符( \\n )结尾。 This is a style which you should follow. 这是您应该遵循的样式。 Otherwise the output may not show up immediately because of buffering. 否则,由于缓冲,输出可能不会立即显示。

Some more details: the feof function only checks if the end of file marker has been set . 更多详细信息: feof函数仅检查是否已设置文件结尾标记 But when the fgetc function notices that it has reached the end of file, this marker has not been set yet. 但是,当fgetc函数注意到它已经到达文件末尾时,此标记尚未设置。 Instead, the fgetc function returns EOF in that case. 相反,在这种情况下, fgetc函数将返回EOF

Oh, and please change the types of your variables. 哦,请更改变量的类型。

char Byte; /* this is wrong. */
int Byte; /* this is correct. */

See any good introductory book on Programming in C for the details. 见C对编程有什么好的入门书籍的详细信息。

What about this new program that uses a different logic: 这个使用不同逻辑的新程序呢?

#include <stdio.h>
int main()
{
    char src[50], tgt[53], ch;
    printf ("Enter file name: ");
    gets (src);
    fs = fopen (src, "r");
    if (fs == NULL)
    {
        printf ("Error while opening file!\n");
        return 1;
    }
    sprintf (tgt, "%s.ed", src);
    ft = fopen (tgt, "w");
    while ((ch = fgetc (fs)) != EOF)
        fputc (~ch, ft);
    fclose (fs);
    fclose (ft);
    remove (src);
    rename (tgt, src);
    return 0;
}

There is no need to write separate functions/programs for both the purposes. 无需为这两种目的编写单独的函数/程序。 Also, the same file will be encrypted by printing the one's complement of a file to another file and renaming the new one to the older one after deleting the older one. 同样,通过删除一个文件的补编到另一个文件,并在删除旧文件后将新文件重命名为旧文件,将对同一文件进行加密。
Overall: This is very simple utility! 总体而言:这是非常简单的实用程序!

Before I explain the solution to the above code, Let me tell you these things first. 在解释上述代码的解决方案之前,让我先告诉您这些事情。 Beaware of unneccessary defination of variables in your program. 小心程序中不必要的变量定义。 I see lots of memory wastage in your code.Everyone can write a program but the one makes it more simpler gets the crown.Remember that when you work on programming. 我看到代码中有很多内存浪费,每个人都可以编写一个程序,但是使程序更简单的人就可以了。请记住在进行编程时。

I see Unneccessary variable i,defination in your Encrypt and Decrypt functions. 我在您的Encrypt和Decrypt函数中看到不必要的变量i,defination。 and There is no need to go for a new byte char defination You can sort off make it as 并且不需要进行新的字节char定义您可以将其整理为

   byte=byte+25 \\ even that makes your work no need of Newbyte char variable.

Erase the int n,int i definations to make your code better.And the most important thing you really got to know is 删除int n,int i定义以使您的代码更好。您真正了解的最重要的事情是

    you cannot use char a;a=getc(Filepointer);

remember the EOF returns -1 when it reaches to the end of file and if your using a char .It doesnot work. 请记住,EOF到达文件末尾并且使用char时将返回-1。 Char data type can only handle positive data .Even if you assign -1 to char, it internally saves it as positive number you can check that thing on google. Char数据类型只能处理正数。即使您为char分配-1,它也会在内部将其保存为正数,您可以在google上检查该值。

      so never use char data type for checkin EOF use int datatype 

and as Ronald mentioned you make it as 正如罗纳德提到的,

       while((Byte=getc(Filepointer))!=EOF)

Thats the error you made.Make it as int datatype.And please check the previous questions.Becuase its actually a duplicate question.Some people can Treat as downvote. 那就是你犯的错误,将其设为int数据类型,并请检查前面的问题,因为它实际上是一个重复的问题,有些人可以将其视为低票。

The better style for encrypting and decrypting is using bitwise operations rather than addition 加密和解密的更好方式是使用按位运算,而不是加法

            Byte=Byte^200; To encrypt  \\ just a sample 
            Byte=Byte^200; To  decrypt \\ you can make more complicated

That how you gotta do. 那你该怎么做。 It gives you more security compared to adding 25 to your ACSII char.YOu can even encrypt it giving some predefined rules to it.Hope you got the answer and solved you problem.Thank you 与在ACSII字符中添加25个字符相比,它提供了更高的安全性.YOu甚至可以对其加密,并为其提供一些预定义的规则。希望您能得到答案并解决了您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM