如何用C语言对文件进行加密和解密?

Python015

如何用C语言对文件进行加密和解密?,第1张

对于加密要求不高的完全可以自己定义规则来进行加密。这种加密是很简单很自由的,例如你在存文件的时候可以将文件中的每个字符都加上一个数,然后读取该文件的时候再每个字符相应地减去那个数,即可实现就简单的加密,这样你储存的文件看上去就是乱码了。只是这个规则太简单,规则你可以自己定,加密与解密对着来就行了。

下面程序用异或操作对文件进行加密和解密

/******************设计思路******************/

//根据用户输入的加密/机密密码

//每次都拿原文件和密码等长度的一个字符串和密码

//对应元素异或进行加密/解密

//另外因为是用异或方法,所以加密和解密就是同一个程序

//即按照同样的加密即是对文件的解密

#include

#include

#include

#include

#include

charfilename[256]//原文件

charpassword[256]//加密/解密密码

constcharfilenametemp[]="temp15435255435325432543.temp"//加密/解密中间文件

voidinputpass(char*pass)//密码输入以"******"显示

voidmain(){

FILE*fp//加密/解密的文件

FILE*fptemp//加密/解密过程临时文件

intpwdlen//密码长度

inti=0//计数器

charch=0//读入的字符

printf("请输入要加密/解密的文件名(全路径名):\n")

gets(filename)

if((fp=fopen(filename,"rb"))==NULL){

printf("找不到文件%s\n",filename)

exit(1)

}//if

printf("请输入要加密/解密的密码:\n")

inputpass(password)

pwdlen=strlen(password)

if(pwdlen==0){

printf("密码不能为空,加密/解密失败\n")

exit(1)

}//if

fptemp=fopen(filenametemp,"wb")//打开中间文件

while(1){

ch=fgetc(fp)//从原文件读入一个字符

if(feof(fp)){//已经读到文件尾

break//退出循环

}

ch^=password[i++]//对原字符和密码进行异或操作

fputc(ch,fptemp)//将异或结果写入中间文件

if(i==pwdlen){//使得原文件每和密码长度相同的固定长度异或加密

i=0

}

}//while

fclose(fp)//关闭打开原文件

fclose(fptemp)//关闭打开中间文件

remove(filename)//删除原文件

rename(filenametemp,filename)//将中间文件重命名为原文件

printf("加密/解密成功\n")//至此加密/解密成功

}

//密码输入以"******"显示

voidinputpass(char*pass){

inti=0

charc

while(isprint(c=getch())){

pass[i++]=c

//printf("*")

}

pass[i]='\0'

printf("\n")

}

C语言设计一个简单的加密解密程序如下:

加密程序代码:

#include<stdio.h>

main()

{

char c,filename[20]

FILE *fp1,*fp2

printf("请输入待加密的文件名:\n")

scanf("%s",filename)

fp1=fopen(filename,"r")

fp2=fopen("miwen.txt","w")

do

{

c=fgetc(fp1)

if(c>=32&&c<=126)

{

c=c-32

c=126-c

}

if(c!=-1)

fprintf(fp2,"%c",c)

}

while(c!=-1)

}

解密程序代码:

#include<stdio.h>

#include<string.h>

main()

{

char c,filename[20]

char yanzhengma[20]

FILE *fp1,*fp2

printf("请输入待解密文件名:\n")

scanf("%s",filename)

printf("请输入验证码:\n")

scanf("%s",yanzhengma)

if(strcmp(yanzhengma,"shan")==0)

{

fp1=fopen(filename,"r")

fp2=fopen("yuanwen.txt","w")

do

{

c=fgetc(fp1)

if(c>=32&&c<=126)

{

c=126-c

c=32+c

}

if(c!=-1)

fprintf(fp2,"%c",c)

}

while(c!=-1)

}

else

{

printf("验证码错误!请重新输入:\n")

scanf("%s",filename)

}

}