#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#define BUF_SIZE 1024
/********************************************************************
* 函数名:encrypt_file
* 功 能: linux下对文件加密及解密
* 参 数: char *rpath为源文件路径及文件名
* char *wpath为加密后的文件要保存的路径及名称
* int secret_key为加密密码
* 返回值: 0表示成功,-1表示失败
********************************************************************/
int encrypt_file(char *rpath,char *wpath,int secret_key)
{
int i = 0;
int Readfd,Writefd;
int Writebytes;
int Readbytes = 1;
char buf[BUF_SIZE];
Readfd = open(rpath,O_RDWR);
if(Readfd<0)
{
printf("open file failed\n");
return -1;
}
Writefd = open(wpath,O_RDWR|O_CREAT|O_APPEND);
if(Writefd<0)
{
printf("open file failed\n");
return -1;
}
while(Readbytes)
{
memset(buf,0,sizeof(buf));
Readbytes = read(Readfd,buf,sizeof(buf));
printf("Readbytes=%d\n",Readbytes);
for(i=0;i<Readbytes;i++)
{
buf[i] = buf[i] ^ secret_key;
}
if(Readbytes)
{
Writebytes = write(Writefd,buf,Readbytes);
printf("Writebytes=%d\n",Writebytes);
}
}
return 0;
}
int main(int argc,char *argv[])
{
int ret = 0;
int SecretKey = 0;
char *ReadPath;
char *WritePath;
ReadPath = argv[1];
WritePath = argv[2];
SecretKey = (int)argv[3];
if(4 == argc)
{
ret = encrypt_file(ReadPath,WritePath,SecretKey);
if(ret < 0)
{
printf("encrypt file failed\n");
return -1;
}
}
else
{
printf("input param error,please input again!\n");
}
return 0;
}
/********************************************************************
使用说明:
加密过程:
gcc encpypt.c -o encrypt
./encrypt a.c b.c 123xyz
解密过程:
./encrypt b.c c.c 123xyz
说明: a.c为源文件,b.c为加密后的文件,c.c为解密后的文件,
即a.c和c.c是一样的,123xyz为密码
后缀为.c,.o,.h,.d等等任何文件都可加密,包括txt文档
**********************************************************************/