黑曜石和绿幽灵:C++密码编程

来源:百度文库 编辑:高校问答 时间:2024/04/29 21:37:02
现有一道C++的编程题目,要求如下:从键盘输入一串文字,然后对其进行加密。密码的算法是:对输入的字符串反复加4,9,6,2,8,7,3。然后在32(‘’)~122(‘z’)之间取模。我作出了加密的算法,但是不知怎么完成解密,求大家帮我。希望可以在今天就搞定,因为明天就要上交了!
附加密程序:
#include<iostream>
#include <afxcoll.h>
#include<algorithm>
#include<string>
using namespace std;
void main()
{
int i=0,key[7]={4,9,6,2,8,7,3};
char ch;
string pass,pass_copy,text;
cout<<"请输入明文:"<<endl;
//----------------------加密过程
for(ch;((ch=cin.get())!='\n');)
{ ch=ch+key[i++];
if(i>6||ch=='\n')
i=0;
if(ch>122||ch<32)
ch=ch%122+32;
pass=pass+ch;
}
cout<<"密文是:\n"<<pass<<endl;
}
结果是:
请输入明文:
the result of 3 and 2 is not 8
密文是:
xqk"zlvyuz"wm#7)gpl'5$ry"vvw$A

#include<iostream>
//#include <afxcoll.h>
//#include<algorithm>
#include <windows.h>
#include<string>
using namespace std;

void main()
{
int i=0,key[7]={4,9,6,2,8,7,3};
char ch;
string pass,text;
cout<<"请输入明文:"<<endl;
//----------------------加密过程
for(ch;((ch=cin.get())!='\n');)
{
ch=ch+key[i++];
if(i>6||ch=='\n')
i=0;
if(ch>122||ch<32)
ch=ch%122+32;
pass=pass+ch;
}
cout<<"密文是:\n"<<pass<<endl;

//----------------------解密过程

char *strs=new char[pass.length()];//将字符串转换为字符数组
strs[pass.length()]='\0';
pass.copy(strs,pass.length(),0);
i=0;
for(int j=0;j<pass.length();j++)
{
ch=strs[j];
ch-=key[i++];
if(i>6||ch=='\n')
i=0;
if(ch<32) // 由于你的加密算法并不是一一对应,即不一定可逆,需要扩展
{ ch=ch-32;
ch=ch+122;
}
text=text+ch;
}
cout<<"解密后是:\n"<<text<<endl;
delete[]strs;
}

#include "iostream.h"
#include "process.h"
#include "string.h"
int decode(char b[]);
void main()
{
char str[80];
int succ;
while (1)
{
cout<<"请输入经过加密的字符串(长度不得超过80,"0"退出):";
cin>>str;
if (strcmp(str,"0")==0)
{
exit(0);
}
succ=decode(str);
if(succ==1)
{
cout<<"原文为:"<<str<<'\n';
}
else
{
cout<<"字符串有小写字母以外的字符,解密失败"<<'\n';
}
}
}
int decode(char b[])
{
char list[27]="kczuytmxsejdlribnhvawofpgq";
int i,j;
i=0;
while (b[i]!='\0')
{
if((b[i]>='a')&&(b[i]<='z'))
{
j=0;
while(list[j]!=b[i])
{
j++;
}
b[i]=j+97;
i++;
}
else
{
return 0;
}
}
return 1;
}
我是在书上找的道类试的题
毕竟我还学到那去,
等我学到那部分了我一定给你个漂亮的答案,希望我找的例子对你有帮助
呵呵