// 一次一密加密解密算法实现.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<ctime>
#include<fstream>
using namespace std;
#define MAX 1000
string key = "";
int len;
//加密 解密算法
string bitcode(string str,string key,const int len)
{
int i;
string data = "";
for(i=0;i<len;i++)
{
data += str[i]^key[i];
}
return data;
}
//加密 解密密钥
string generateKey(const int len)
{
srand((unsigned)time(NULL));
string k = "";
for(int i= 0;i<len;i++)
k += rand()%10 +'0';
return k;
}
int _tmain(int argc, _TCHAR* argv[])
{
//可以不用这么繁琐,为了可以练习文件操作
char cmd;
do{
//把输入的字符串放在文件中
ofstream file1_out("Data.txt",ios::out|ios::trunc);
string data;
cout<<"请输入明文:"<<endl;
getline(cin,data);
int len = data.length();
file1_out<<data;
file1_out.close();
//从文件中读出字符串
ifstream file1_in("Data.txt",ios::in);
string BefEcry ="";
while(!file1_in.eof())
{
BefEcry += file1_in.get(); //BefEcry 后面还有一个换行符
}
//去掉BefEcry 后面的换行符
string::iterator it1 = BefEcry.end();
BefEcry.erase(it1-1,it1);
cout<<"**************"<<endl;
cout<<"明文为:"<<endl;
cout<<BefEcry<<endl;;
file1_in.close();
key = generateKey(len);
cout<<"加密密钥为:"<<endl;
cout<<key<<endl;
string Encryped;
//加密
Encryped = bitcode(BefEcry,key,len);
//把加密后的字符串写入文件中
ofstream file2_out("Encryption.txt",ios::out|ios::trunc);
file2_out<<Encryped;
file2_out.close();
cout<<"加密后的密文为:"<<endl;
cout<<Encryped<<endl;
//从文件中读出字加密符串
ifstream file2_in("Encryption.txt",ios::in);
string Decrypted;
while(!file2_in.eof())
{
Decrypted += file2_in.get(); //Decrypted后面还有一个换行符
}
//去掉Decrypted 后面的换行符
string::iterator it2 = Decrypted.end();
Decrypted.erase(it2-1,it2);
file2_in.close();
//解密
Decrypted = bitcode(Decrypted,key,len);
cout<<"解密后的明文为:"<<endl;
cout<<Decrypted<<endl;;
cout<<"继续吗?(Y/n):";
cin>>cmd;
}while(cmd=='y'||cmd=='y');
system("pause");
return 0;
}
------------------------------------------------------程序测试-----------------------------------------------
请输入明文:This is a program which is about Encryption and Decryption!
**************
明文为:
This is a program which is about Encryption and Decryption!
加密密钥为:
37512943377123677155495235224596620201331234081461349323048
加密后的密文为:
g_\BPGRGC]TDVZB]]Z]ZFSVZLBw^QBHCGX]]QVUrTPF@CFZ_Z
解密后的明文为:
This is a program which is about Encryption and Decryption!
继续吗?(Y/n):n
请按任意键继续. . .