- 积分
- 601
- UID
- 552
- 在线时间
- 小时
- 最后登录
- 1970-1-1
|
发表于 2006-3-7 14:51:50
|
显示全部楼层
http://blog.csdn.net/sun428/archive/2005/09/23/488267.aspx
这是以前上C++课时写的一道作业题,应该算是作业中比较具有实用价值的了。
该程序用于练习读写文件,其主要思想就是按二进制字节读取文件,将所读取的数据与一个随机生成的密钥(一个0到255的无符号整数)进行异或运算然后再写入一个新的文件(密钥保存在新生成文件的第一个字节)。解密时,先读出密钥然后对接下来读入的数据再与密钥进行异或操作并写入新文件,即可得到加密前的原文件。
采用异或运算的好处在于两次异或即得原数据。
该算法属于加密算法中最简单的一个,安全性较差,不过平时个人用用嘛倒也可以。
程序源代码如下:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <time.h>
#define FILENAMESIZE 50 //文件名长度大小
//////////// function prototype /////////////
void Encrypt(); // 加密函数
void Decrypt(); // 解密函数
//////////// main function /////////////
int main()
{
cout << "请选择你要进行的操作" << endl
<< "1-加密文件" << endl
<< "2-解密文件 " << endl
<< "(1/2):";
int response; //用户选择操作
do
{
cin >> response;
}while( response != 1 && response != 2 );
if( response == 1 )
Encrypt(); //加密文件
else
Decrypt(); //解密文件
return 0;
}
///////////// programer-defined function /////////////
//==============加密函数===============
void Encrypt()
{
// 输入源及目的文件
cout << "请输入要加密的文件:";
char sour_file[FILENAMESIZE];
cin >> sour_file;
cout << "请输入目标文件:";
char dest_file[FILENAMESIZE];
cin >> dest_file;
ifstream infile( sour_file, ios::in | ios::nocreate | ios::binary );//输入文件
ofstream outfile( dest_file, ios::out | ios::binary ); //输出文件
if( ! infile || ! outfile ) //打开文件失败
{
cerr << "! Failed to open the necessary files!" << endl;
exit(1);
}
// 生成密钥
srand( (unsigned)time( NULL ) );
char key = rand() % 256;
outfile.write( &key, 1 );
// 加密文件
char ch;
while( infile.read( &ch, 1 ) )
{
ch ^= key;
outfile.write( &ch, 1 );
}
// 关闭文件
infile.close();
outfile.close();
cout << "加密成功!" << endl;
}
//==============解密函数================
void Decrypt()
{
// 输入源及目的文件
cout << "请输入要解密的文件:";
char sour_file[FILENAMESIZE];
cin >> sour_file;
cout << "请输入目标文件:";
char dest_file[FILENAMESIZE];
cin >> dest_file;
ifstream infile( sour_file, ios::in | ios::nocreate | ios::binary );//输入文件
ofstream outfile( dest_file, ios::out | ios::binary ); //输出文件
if( ! infile || ! outfile ) //打开文件失败
{
cerr << "! Failed to open the necessary files!" << endl;
exit(1);
}
// 读取密钥
char key;
infile.read( &key, 1 );
// 解密文件
char ch;
while( infile.read( &ch, 1 ) )
{
ch ^= key;
outfile.write( &ch, 1 );
}
// 关闭文件
infile.close();
outfile.close();
cout << "解密成功!" << endl;
} |
|