C语言(文件加解密)

1,592 阅读2分钟

经过上一篇文章的学习,已经熟悉了文件的基本操作。本文主要学习使用C语言,对文件进行加密和解密。

在c语言,文件主要分为文本文件和二进制文件,因此主要是对这两种文件进行加解密。

文本文件加解密

原文件

运行结果

/*
加密
对每一个字符进行 异或运算
规则:1^1=0, 0^0=0, 1^0=1, 0^1=1 同为0,不同为1
*/
void crpypt(char file_path[],char crpypt_path[] ){
	//打开文件
	FILE *file_p = fopen(file_path,"r");
	FILE *crpy_p = fopen(crpypt_path,"w");
	//一次读取一个字符
	char ch;
	//EOF:end of file
	while ((ch = fgetc(file_p)) != EOF){
		//写入(异或运算)
		fputc(ch ^ 9, crpy_p);
	}
	//关闭
	fclose(file_p);
	fclose(crpy_p);
	printf("加密完成");
}
void main(){
	char *path = "D:\\mytest.txt";
	char *crpypt_path = "D:\\crpypt_mytest.txt";
	char *decrypt_path = "D:\\decrpypt_mytest.txt";
	crpypt(path,crpypt_path);
	getchar();
}

运行结果

得到加密文件

运行结果

运行结果

文本文件解密

void decrpypt(char crypt_path[], char decrypt_path[]){
	//打开文件
	FILE *crpypt_p = fopen(crypt_path, "r");
	FILE *decrpypt_p = fopen(decrypt_path, "w");
	//一次读取一个字符
	char ch;
	//EOF:end of file
	while ((ch = fgetc(crpypt_p)) != EOF){
		//写入(异或运算)
		fputc(ch ^ 9, decrpypt_p);
	}
	//关闭
	fclose(crpypt_p);
	fclose(decrpypt_p);
	printf("解密完成");
}
void main(){
	char *path = "D:\\mytest.txt";
	char *crpypt_path = "D:\\crpypt_mytest.txt";
	char *decrypt_path = "D:\\decrpypt_mytest.txt";
	decrpypt(crpypt_path, decrypt_path);
	getchar();
}

运行结果

解密得到的文件

运行结果

运行结果

以上就是对文本文件进行加解密,算法:对文本文件的字符进行异或运算。

二进制文件加解密

二进制文件加密

/*
二进制文件加解密
读取二进制文件中的数据时,一个一个字符读取
对每一个字符进行 异或运算
*/
/*
二进制文件加解密
读取二进制文件中的数据时,一个一个字符读取
对每一个字符进行 异或运算
*/
void crpypt(char file_path[], char crpypt_path[], char password[]){
	//打开文件
	FILE *file_p = fopen(file_path, "rb");
	FILE *crpy_p = fopen(crpypt_path, "wb");
	//一次读取一个字符
	int ch;
	int i = 0; //循环使用密码中的字母进行异或运算
	int pw_len = strlen(password); //密码的长度
	while ((ch = fgetc(file_p)) != EOF){ //End of File
		//写入(异或运算)
		fputc(ch ^ password[i % pw_len], crpy_p);
		i++;
	}
	//关闭
	fclose(file_p);
	fclose(crpy_p);
	printf("加密完成");
}
/*
密码:password
*/
void main(){
	char *path = "D:\\timg.jpg";
	char *crpypt_path = "D:\\crpypt_timg.jpg";
	char *decrypt_path = "D:\\decrpypt_timg.jpg";
	crpypt(path, crpypt_path, "password");
	getchar();
}

原文件

运行结果

加密后

运行结果

运行结果

二进制文件解密

//解密
void decrpypt(char crypt_path[], char decrypt_path[], char password[]){
	//打开文件
	FILE *crpypt_p = fopen(crypt_path, "rb");
	FILE *decrpypt_p = fopen(decrypt_path, "wb");
	//一次读取一个字符
	int ch;
	//循环使用密码中的字母进行异或运算
	int i = 0; 
	//密码的长度
	int pw_len = strlen(password);
	//EOF:end of file
	while ((ch = fgetc(crpypt_p)) != EOF){
		//写入(异或运算)
		fputc(ch ^ password[i % pw_len], decrpypt_p);
		i++;
	}
	//关闭
	fclose(crpypt_p);
	fclose(decrpypt_p);
	printf("解密完成");
}


/*
密码:password
*/
void main(){
	char *path = "D:\\timg.jpg";
	char *crpypt_path = "D:\\crpypt_timg.jpg";
	char *decrypt_path = "D:\\decrpypt_timg.jpg";
	decrpypt(crpypt_path, decrypt_path, "password");
	getchar();
}

运行结果:

运行结果

运行结果

运行结果

二进制文件的加载跟文本文件的加密,这里使用的都是同样的算法:异或运算。

注意: 二进制文件和文本文件读写不一样 文本文件读写分别使用:"r","w" 二进制文件读写分别使用:"rb","wb"。

以上就是使用异或运算对文件进行加解密的实例。