一次一密加密解密算法实现

 

// 一次一密加密解密算法实现.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
请按任意键继续. . .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值