1.题目:
Caesar密码作为一种最为古老的对称加密体制,它的基本思想是:通过把字母移动一定的位数来实现加密和解密。明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推X将变成A,Y变成B,Z变成C。由此可见,位数就是Caesar密码加密和解密的密钥。
用Caesar密码对下列明文进行加密。
“Public-key cryptography, also known as asymmetric cryptography, is a class of cryptographic protocolsbased on algorithms that require two separatekeys, one of which is secret (or private) and one of which is public.”加密密钥为k=11;
对密文” Qbspbz Jhlzhy dhz ivyu pu Yvtl vu 89 vy 80 Qbsf 877 IJ puav aol wylzapnpvbz Qbsphu jshu. “进行解密,解密密钥为k=7
2.要求
大写字母加(解)密后仍为大写字母,小写字母(加)解密后仍为小写字母,数字解密后仍为数字,其他标点符号原样输出。
3.代码
#include<iostream>
#include<cmath>
#include<string>
#include<stdio.h>
using namespace std;
void MC(string &s1, int k1) //加密
{
for(unsigned int i=0; i<s1.length(); i++)
{
if(97 <= s1[i] && s1[i] <= 122) //小写
{
s1[i] = ((s1[i] + k1 - 97) % 26) + 97;
cout<<s1[i];
}
else if(65 <= s1[i] && s1[i] <= 90) //大写
{ s1[i] = ((s1[i] + k1 - 65) % 26) + 65;
cout<<s1[i];
}
else if(48<= s1[i] && s1[i] <= 57) //数字
{
s1[i] = ((s1[i] + k1 - 48) % 10) + 48;
cout<<s1[i];
}
else
cout<<s1[i];
}
cout<<endl;
}
void CM(string &s2, int k2) //解密
{
for(unsigned int i=0; i<s2.length(); i++)
{
if(97 <= s2[i] && s2[i] <= 122) //小写
{
s2[i] = ((s2[i] - k2 - 122) % 26) + 122;
cout<<s2[i];
}
else if(65 <= s2[i] && s2[i] <= 90) //大写
{ s2[i] = ((s2[i] - k2 - 90) % 26) + 90;
cout<<s2[i];
}
else if(48 <= s2[i] && s2[i] <= 57) //数字
{
s2[i] = ((s2[i] - k2 - 57) % 10) + 57;
cout<<s2[i];
}
else
cout<<s2[i];
}
cout<<endl;
}
int main()
{
string s1 = "“Public-key cryptography, also known as asymmetric cryptography, is a class of cryptographic protocols based on algorithms that require two separatekeys, one of which is secret (or private) and one of which is public.”";
string s2 = "“Qbspbz Jhlzhy dhz ivyu pu Yvtl vu 89 vy 80 Qbsf 877 IJ puav aol wylzapnpvbz Qbsphu jshu.”";
int k1, k2; //密钥
cin>>k1>>k2;
cout<<"加密后的密文为:"<<endl;
MC(s1, k1);
cout<<endl;
cout<<"解密后的明文为:"<<endl;
CM(s2, k2);
return 0;
}
4.结果
5.总结
(1)不能用cin输入带有空格的字符串。
(2)’\n’和endl在C++里面具有同样的换行效果。
(3)也可以不把明文和密文提前输入,可先定义字符串s1,s2,再使用getline(cin,s1)输入字符串。也可使用循环语句,选择是加密还是解密。