如何使用C语言给自己的文件上把锁

最近自学了一点密码学的东西,也对一些常见的加密算法有过一些了解,但是不管是CSDN 还是博客园这样的论坛一直很少有给文件加密的博客或是代码,今天想介绍一下使用C语言给文件加密的一个小demo
其实文件以二进制格式打开的情况向就相当于一个超大的字符串,核心思想就是每次从文件中读入一定长度的数据进行加密,然后再以二进制的形式写入输出文件中,每次读入一定长度的串而不是一口气全读进来的原因是怕文件太大,内存爆掉。
直接上代码:

//MyFileEncryptCode
#include<stdio.h>
#include<string.h>
#include<string.h>
#include<windows.h>

int main()
{
     
	int filelength,keylength,i; 
	unsigned char key[100],infilepath[256],outfilepath[256],buffer[256]; 
	FILE * rp;
	FILE * wp;
	while(1)
	{
     
	printf("请输入待加密文件的完整路径名:");
	gets(infilepath);
    if((rp=fopen(infilepath,"rb"))==NULL)
    {
     
      printf("Can't open the file\n");
      continue;
    }
    printf("请输入加密输出文件的完整路径名:");
    gets(outfilepath);
    if((wp=fopen(outfilepath,"wb"))==NULL)
    {
     
      printf("Can't open the file\n");
      continue;
    }
    printf("请输入密钥:");
    gets(key);
    keylength = strlen(key);
    fseek(rp,0L,SEEK_END);
    filelength=ftell(rp);
    fseek(rp,0L,SEEK_SET);
    while(filelength>keylength)
	{
     
		fread(buffer,sizeof(unsigned char),keylength,rp);
		for (i=0;i<keylength;i++)
		{
     
			buffer[i] = buffer[i]^key[i];
			buffer[i] = ~buffer[i];
			buffer[i] = (buffer[i] + 0X36) % 0X100;
		}
		fwrite(buffer,sizeof(unsigned char),keylength,wp);
		filelength -= keylength;
	}	
	fread(buffer,sizeof(unsigned char),filelength,rp);
	for (i=0;i<filelength;i++)
		{
     
			buffer[i] = buffer[i]^key[i];
			buffer[i] = ~buffer[i];
			buffer[i] = (buffer[i] + 0X36) % 0X100;
		}
	fwrite(buffer,sizeof(unsigned char),filelength,wp);
	fclose (rp);
	fclose (wp);
	printf("加密成功,文件保存在");
	puts(outfilepath);
	printf("中\n\n");
}
return 0;
}

这里使用的加密算法非常简单,简单到甚至算不上一个加密算法,仅仅只是将每个字节先与密钥异或,再取反,最后求余。这样的好处是时间复杂度较低,缺点当然是安全性低,不过对于我们一般的加密而言,这已经是足够了的。
至于解密算法,只需要将加密过程逆向即可,即

while(filelength>keylength)
	{
     
		fread(buffer,sizeof(unsigned char),keylength,rp);
		for (i=0;i<keylength;i++)
		{
     
			buffer[i] = (buffer[i] + 0XCA) % 0X100;
			buffer[i] = ~buffer[i];
			buffer[i] = buffer[i]^key[i];
		}
		fwrite(buffer,sizeof(unsigned char),keylength,wp);
		filelength -= keylength;
	}	
	fread(buffer,sizeof(unsigned char),filelength,rp);
	for (i=0;i<filelength;i++)
		{
     
			buffer[i] = (buffer[i] + 0XCA) % 0X100;
			buffer[i] = ~buffer[i];
			buffer[i] = buffer[i]^key[i];
		}
	fwrite(buffer,sizeof(unsigned char),filelength,wp);

你可能感兴趣的:(c语言,密码学)