简单加密方式为将要加密的文件,通过设置的密码加和计算一个值,将这个值与原始文件相加,并将初始的密码存入文件的前十个字节。
解密为读取文件的前十个字节,加和,将加密值减和写入文件。
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int encryption(const char * file_in,const char * file_out,char *sec);
int decrypt(const char * file_in,const char * file_out);
int main()
{
string x;
cout << " 1.加密 2.解密" << endl;
cout << ">> ";
cin >> x;
if (x == "1")
{
encryption("src.zip","src.zip.in","positec001");
}
else if (x == "2")
{
decrypt("src.zip.in","src.zip");
}
else
{
cout << "请按照要求输入。。。。" << endl;
}
return 0;
}
int encryption(const char * file_in,const char * file_out,char *sec)
{
fstream fp01,fp02;
fp01.open(file_in, ios::in | ios::binary);
if (fp01.fail())
{
cout << " 输入文件读取异常,请检查文件名是否有误";
return -1;
}
fp02.open(file_out, ios::out | ios::binary);
if (fp02.fail())
{
cout << "输出文件读取异常,请检查文件名是否有误";
return -2;
}
size_t Size = strlen(sec);
if(Size<10)
{
cout << "secret too short";
return -3;
}
char ch_m = 0,ch=0;
for(int i=0;i<10;i++)
{
fp02.write(&sec[i], 1);//将加密写入前十位
ch_m+=sec[i];//累加结果
}
while (true)
{
fp01.read(&ch, 1);
if (fp01.eof())
{
break;
}
ch=ch+ch_m;
fp02.write(&ch, 1);
}
fp01.close();
fp02.close();
return 1;
}
int decrypt(const char * file_in,const char * file_out)
{
fstream fp01(file_in, ios::in | ios::binary);
if (fp01.fail())
{
cout << "输入文件读取异常,请检查文件名是否有误";
return -2;
}
fstream fp02(file_out, ios::out | ios::binary);
if (fp02.fail())
{
cout << "输出文件读取异常,请检查文件名是否有误";
return -1;
}
char ch_m = 0,ch=0;
for(int i=0;i<10;i++)
{
fp01.read(&ch, 1);//将加密写入前十位
ch_m+=ch;//累加结果
}
while (true)
{
fp01.read(&ch, 1);
if (fp01.eof())
{
break;
}
ch=ch-ch_m;
fp02.write(&ch, 1);
}
fp01.close();
fp02.close();
return 1;
}