|
楼主 |
发表于 2006-1-6 12:34
|
显示全部楼层
对以上的程序稍作修改,可变成一个简单实用的文件加密/解密的程序.
对原文件加密时输入加密密码,生成一个已经是乱码的文件
解密时输入同一个密码则可解密,生成一个和原文件一样内容的文件,否则是再次加密.
当然,可以多次加密,然后反序解密,只要密码及顺序没错,应该可以还原的.
- /*encode.cpp*/
- //通过简单的异或对文件加密/解密
- #include<fstream>
- #include<iostream>
- #include<cstdlib>
- #include<string>
- using namespace std;
- void print_error(const char*a,const char* b=" ");
- bool equals(string a,string b);
- char lastChar(string s);
- int main(int argc,char *argv[]){
- if(3!=argc)print_error("usage:encode source dest");
-
- string src(argv[1]); string dest(argv[2]);
- const int LEN=1024; long end;
- char ch[LEN]; int seed=0;
-
- if(equals(src,dest))print_error("usage:the source can't be the dest");
- ifstream in(src.c_str(),ios::binary|ios::ate);
- end=in.tellg();
- in.seekg(0,ios::beg);
- if(!in)
- print_error("Can't open",dest.c_str());
-
- if(lastChar(dest)=='\\'||lastChar(dest)=='/'||lastChar(dest)==':')
- {
- string filename;
- string name;
- if (lastChar(dest)==':')
- {
- filename=dest;
- filename.append("\");
- filename.append(src);
- }else filename=strcat(argv[2],argv[1]);
-
- const char* p=filename.c_str();
- ofstream out(p,ios::binary);
- if(!out)print_error("Can't open the file:",filename.c_str());
- cout<<"请输入加密/解密的密钥(整数如123)"<<endl;cin>>seed;
- while (in.read(ch,LEN))
- {
- for(int i=0;i<in.gcount();i++)ch[i]=ch[i]^seed;
- out.write(ch,LEN);
- }
- char *s=ch;
- int ii=in.gcount();
- for(int i=0;i<ii;i++){ch[i]=ch[i]^seed;out.put(s[i]);}
- if(!in.eof())
- print_error("something wrong!");
- cout<<"成功保存了文件: "<<filename<<" "<<end<<" bytes."<<endl;
- in.close();
- out.close();
- }
- else
- {
- ofstream out(argv[2],ios::binary);
- if(!out)print_error("Can't open ",dest.c_str());
- cout<<"请输入加密/解密的密钥(整数如123)"<<endl;cin>>seed;
- while (in.read(ch,LEN))
- {
- for(int i=0;i<in.gcount();i++)ch[i]=ch[i]^seed;
- out.write(ch,LEN);
- }
- int len=in.gcount();
- char *s=ch;
- for(int i=0;i<len;i++){ch[i]=ch[i]^seed;out.put(s[i]);}
- if(!in.eof())
- print_error("something wrong!");
- cout<<"成功保存了文件:"<<argv[2]<<" "<<end<<" bytes."<<endl;
- in.close();
- out.close();
- }
-
- return 0;
- }
- bool equals(string str1,string str2)
- {
- transform(str1.begin(),str1.end(),str1.begin(),(int(*)(int))tolower);
- transform(str2.begin(),str2.end(),str2.begin(),(int(*)(int))tolower);
- if(str1==str2)return true;
- return false;
- }
- void print_error(const char* a,const char* b){
- cerr<<a<<" "<<b<<endl;
- exit(1);
- }
-
- char lastChar(string s)
- {
- string::iterator p;
- p=s.end();
- return *(p-1);
- }
复制代码 |
|