sun428的专栏

山外青山楼外楼,学无止境!

原创 异或加解密收藏

这是以前上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;
}

发表于 @ 2005年09月23日 22:24:00|评论(loading...)

新一篇: ACM参赛纪念 | 旧一篇: 开篇语

用户操作
[即时聊天] [发私信] [加为好友]
sun428
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
sun428的公告
sun428,雏鸟者。感计算机技术之强大而投诸。技虽低,然狂热甚之。作此Blog乃求尽己之力助之于初之学者,并受点拨于大侠者也。若达此二者莫敢不喜哉!
文章分类
收藏
链接
sun428's blog(RSS)
totoorange——只谈技术(RSS)
史蒂芬的技术博客(RSS)
存档
软件项目交易
Csdn Blog version 3.1a
Copyright © sun428