文件加密和解密实现

code.h

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//加密
void codeFile(char * sourceFile, char * destFile);

//解密
void deCodeFile(char * sourceFile, char * destFile);

 code.c

#include"code.h"

void codeFile(char * sourceFile, char * destFile)
{
	FILE *fp1 = fopen(sourceFile, "r");
	FILE *fp2 = fopen(destFile, "w");

	if (!fp1 || !fp2)
	{
		return;
	}

	char ch;
	while ((ch=fgetc(fp1))!=EOF)
	{
		// # 35
		// 0000 0000 0010 0011  <<4
		short temp = (short)ch;
		temp = temp << 4;

		//1000 0000 0000 0000  |
		//1000 0010 0011 0000  + 0000~1111  0~15

		temp = temp | 0x8000;

		temp = temp + rand() % 16;

		//printf("%d", temp);

		//加密后数据 写入到文件中
		fprintf(fp2, "%hd", temp);
	}
	fclose(fp1);
	fclose(fp2);
}


void deCodeFile(char * sourceFile, char * destFile)
{
	FILE *fp1 = fopen(sourceFile, "r");
	FILE *fp2 = fopen(destFile, "w");

	if (!fp1 || !fp2)
	{
		return;
	}

	short temp;
	while (!feof(fp1))
	{
		fscanf(fp1, "%hd", &temp);

		//1000 0010 0011 1010  << 1
		// 000 0010 0011 10100 >> 5
		//0000 0000 0010 0011

		temp <<= 1;
		temp >>= 5;
		char ch = (char)temp;

		fputc(ch, fp2);
	}
	fclose(fp1);
	fclose(fp2);
}

  main.c

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include"code.h"

void test02() 
{
	codeFile("./config.txt", "./加密文件.txt");
	deCodeFile("./加密文件.txt", "./解密文件.txt");
}

int main() 
{
	//随机数种子
	srand((unsigned int)time(NULL));
	test02();

	system("pause");
	return EXIT_SUCCESS;
}

ps: %hd:打印以十进制显示short类型的整数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值