1. 程式人生 > >C語言實現任何檔案的加密解密

C語言實現任何檔案的加密解密

使用命令提示符,實現任何檔案的加密和解密功能。

程式碼如下:

//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<time.h>
#include<sys/stat.h>


#pragma warning(disable:4996)

//加密
void Encryption(char *p, size_t n)
{
	for (int i = 0; i < n;++i)
	{
		*p += 7;
	}
}

//解密
void Decrypt(char *p, size_t n)
{
	for (int i = 0; i < n;++i)
	{
		*p -= 7;
	}
}

char *EnOrDe = {0};

int main(int argc, char *args[])
{
	clock_t c1 = clock();//系統當前時間,毫秒為單位

	char *FileNameSrc = (char *)calloc(160, sizeof(char));//待操作檔案

	char *p2 = (char *)calloc(200, sizeof(char));//操作後文件名

	//從命令列獲取檔名和要處理的操作
	FileNameSrc = args[1];//檔名,包含路徑

	char *p1 = args[1];

	EnOrDe = args[2];//en表示加密,de表示解密

	/*FileNameSrc =  "E:\\iPhone6-new.txt" ;
	char *p1 = FileNameSrc;
	EnOrDe = "de";*/


	/**********處理生成新的檔名***********/
	//char *p2 = { 0 };
	/*FileNameSrc = p1;*/
	//printf("%s\n", FileNameSrc);
	//printf("%s\n", EnOrDe);

	int index = 0;
	while (*p1)
	{
		if (*p1!='.')
		{
			*p2 = *p1;
			p2++;
			p1++;
			index++;
		}
		else if (*p1 == '.')
		{
			*p2 = '_';
			p2++;
			*p2 = 'H';
			p2++;
			*p2 = '.';
			p2++;
			p1++;
			index+=2;
		}
	}
	printf("\n");
	printf("資訊摘要:\n");
	printf("--------------------------------------\n");
	printf("原檔案:%s\n", FileNameSrc);
	printf("操作:%s  (en——加密,de——解密)\n", EnOrDe);
	printf("預計結果檔案:%s\n", p2 - index - 1);
	printf("--------------------------------------\n\n");
	printf("請稍後,玩命處理中......\n");

	char *FileNameDst = p2 - index - 1;

	FILE *pr = fopen(FileNameSrc, "rb");
	FILE *pw = fopen(FileNameDst, "wb");

	struct stat st = { 0 };
	size_t fileSize = st.st_size;//以位元組為單位

	//char *buf = NULL;
	//if (fileSize<1024*1024)//小於1M
	//{
	//	buf = malloc(sizeof(char) * 1024 * 20);//分配20K
	//}
	//else
	//{
    //  buf = malloc(sizeof(char)*fileSize / 10);
	//}
	char *buf = calloc(1024 * 1024 * 25, sizeof(int));//分配100M

	/*************定義函式指標***************/
	void(*pFunc)(char *, size_t);
	pFunc = NULL;
	if (strcmp(EnOrDe, "en") == 0)
	{
		pFunc = Encryption;
	}
	else if (strcmp(EnOrDe, "de") == 0)
	{
		pFunc = Decrypt;
	}
	/*************定義函式指標***************/


	while (!feof(pr))
	{
		//memset(buf, 0, sizeof(buf));//calloc自動初始化為0
		size_t  res = fread(buf, sizeof(char), sizeof(buf), pr);

		pFunc(buf, res);

		fwrite(buf, sizeof(char), res, pw);
	}
	fclose(pr);
	fclose(pw);
	printf("\n");
	printf("--------------------------------------\n");
	printf("執行成功!\n所在目錄:%s\n", FileNameDst);
	clock_t c2 = clock();//系統當前時間,毫秒為單位
	printf("耗時:%u毫秒\n", c2-c1);
	printf("--------------------------------------\n");
	return 0;
}
效果: