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

Python010

如何用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")

}

#include "stdio.h"

#include <stdlib.h>

int main(int argc,char *argv[]){

FILE *fp,*fq

int k,t

fp=fopen("AAA12345678901.txt","w+")

if(!fp || (fq=fopen("tmp.txt","w"))==NULL){

printf("Failed to open the file and exit...\n")

return 0

}

printf("Please enter a short passage(letters+space+punctuation,'Enter' end)...\n")

while((t=getchar())!='\n')//为文件输入内容

fputc(t,fp)

printf("Please enter the encryption key(int >0)...\nk=")

while(scanf("%d",&k)!=1 || k<1){//输入加密密钥并判断是否正确

printf("Input error, redo: ")

fflush(stdin)

}

rewind(fp)

while(t=fgetc(fp),!feof(fp))//加密

if(t>='A' &&t<='Z')

fputc(((t-'A')+k)%26+'A',fq)

else if(t>='a' &&t<='z')

fputc(((t-'a')+k)%26+'a',fq)

else

fputc(t,fq)

fclose(fp)//关闭原文件

fclose(fq)//关闭加密后的文件

remove("AAA12345678901.txt")//删除原文件

rename("tmp.txt","AAA12345678901.txt")//将加密后的文件更换为原文件名

printf("\n")

if(fp=fopen("AAA12345678901.txt","r")){

while((t=fgetc(fp))!=EOF)

printf("%c",t)

printf("\nEncryption success!\n")

}

else

printf("\nFailed to open the encrypted file...\n")

fclose(fp)

return 0

}

代码格式和运行样例图片:

#include<stdio.h>

int main()

{char ch

 FILE *fp1,*fp2

 fp1=fopen("d:\\file1.txt","r")

 fp2=fopen("d:\\file2.txt","w")

 printf("加密后的内容:\n")

 while((ch=fgetc(fp1))!=EOF)

 {ch^=0x6a putchar(ch) fputc(ch,fp2)}

 fclose(fp1)

 fclose(fp2)

 printf("\n解密后的内容:\n")

 fp2=fopen("d:\\file2.txt","r")

 while((ch=fgetc(fp2))!=EOF)

 {ch^=0x6a putchar(ch)} 

 return 0 

}