怎么用c语言给文件加密?

C语言用过很长时间,也编写过一些程序。最近看到网上的文件加密软件挺多的,我就想能不能自己也写一个程序,来给文件加密呢,所以我就利用c语言来给文件加密。

 

其操作是指示用户键入一个完整的文件名,包含文件路径和文件名,如后输入加密密码,就可以对指定文件进行加密了。

 

加密的原理:读出文件中的字符,然后与自己输入的加密密码进行异或,然后写到新的文件中。解密过程与加密原理一样。

 

程序编写如下:

 

#include <stdio.h>

#pragma hdrstop

#include <tchar.h>

#pragma argsused

int _tmain(int argc, _TCHAR* argv[])

{

       FILE *file1,*file2;

       int i;

       int paslen;

       char ch;

       char source[30],destin[30],password[10];

       printf("Please input the source file(less than 30 charcters):\n");

       gets(source);

       printf("please input the destination file(less than 30 charcters):\n");

       gets(destin);

       printf("please input the password(less than 10 ditigals):\n");

       gets(password);

       paslen=strlen(password);//获取密码长度

       if((file1=fopen(source,"rb"))!=NULL)

       {

              printf("the source file %s opened successfully.\n",source);

              if((file2=fopen(destin,"wb+"))!=NULL)

              {

                     printf("the destination file %s created successfully\n",destin);

                     ch=fgetc(file1);

                     i=0;

                     while(ch!=EOF)

                     {

                            ch=ch^(password[i++]); //利用密码进行加密

                            if(i>=paslen)

                            i=0;

                            fputc(ch,file2);

                            ch=fgetc(file1);

                     }

                     fclose(file1);

                     fclose(file2);

              }

              else

              {

                     printf("the destination file %s created error\n",destin);

              }

       }

       else

       {

              printf("the source file %s opened error.\n",source);

       }

       getchar();

       return 0;

}

就是这样一个简单的程序,就可以实现文件加密,你也可以试试,另外,您要是还有什么比较不错的方法的话,也可以给我推荐一下。

posted @ 2012-06-18 16:07  T库科技  阅读(3114)  评论(0编辑  收藏  举报