您的位置:首页 > 编程语言 > C语言/C++

文件加密之异或加密(C++实现)

2015-03-03 19:44 239 查看
#include <iostream>

#include <fstream>

#include <string.h>

using namespace std;

//加密函数

void Encryption(char *in_fname,char *out_fname,char *pwd)

{

FILE *in_file,*out_file;

register char ch;

int x;

x=strlen(pwd);

in_file=fopen(in_fname,"rb");//以读的方式打开二进制文件

if(in_file==NULL)//如果打开失败

{

cout<<"Open file error";

exit(1);

}

out_file=fopen(out_fname,"wb");//以写的方式打开二进制文件

if(out_file==NULL)//如果创建失败

{

cout<<"Create file error";

exit(1);

}

//一下两断注释代码,要选其一进行使用

/*

这一断注释代码的功能是只对文件的前几位加密,可以提高读写速度,主要用于视频、音频文件,因为只要这类文件的前几位一经修改,是无法正常播放的。

ch=fgetc(in_file);

for(int i=0;i<=x;i++)

{

fputc(ch^pwd[i],out_file); //fputc函数是向文件写入一位字符

ch=fgetc(in_file);
//fgetc()函数是得到文件的一个字符,会自动使指针后移一位

}

while(!feof(in_file))

{

fputc(ch,out_file);

ch=fgetc(in_file);

}

*/

/*

这一断注释代码的功能是对文件的所有位加密,主要用于文本文件。

while(!feof(in_file))

{

fputc(ch^pwd[i>=x?i=0:i++],out_file);

ch=fgetc(in_file);

}

*/

fclose(in_file);

fclose(out_file);

}

void main()

{

char in_fname[30],out_fname[30],pwd[30];

cout<<"Please input file name which you want to be encrypted:"<<endl;//输入想要加密文件的文件名

cin>>in_fname;

cout<<"Please input file name which which will be output:"<<endl;//输出加密后文件的文件名

cin>>out_fname;

cout<<"Please input password:"<<endl;//输入密码

cin>>pwd;

Encryption(in_fname,out_fname,pwd);//调用加密函数

cout<<"Success!"<<endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: