1.凯撒密码(Caesar Shift)是一种简单的移位密码(The Shift Cipher)
2.一般只对26个字母进行移位
3.对字母A:设移位数(密钥)为key
若key = 3,则结果为D,
若key = 0,则结果为A,
若key = 25,则结果为Z,
若key = 29,则结果为D。
4.对字母Z:
若key = 3,则结果为C,
若key = 0,则结果为Z,
若key = 25,则结果为Y,
若key = 29,则结果为C。
Caesar C++实现代码
#include<iostream>
#include<string>
using namespace std;
//加密
void encrypt(string &s, int key){
char ch = '\0';
for(unsigned int i=0;i < s.length();i++){
if('a' <= s[i] && s[i] <= 'z')
ch = 'a';
else
ch = 'A';
if('A' <= s[i] && s[i] <= 'Z' || 'a' <= s[i] && s[i] <= 'z')
s[i] = ch + (s[i] - ch + key) % 26;//实现字母之间的循环移位
}
}
//解密
void decrypt(string &s, int key){
char ch = '\0';
for(unsigned int i=0;i < s.length();i++){
if('a' <= s[i] && s[i] <= 'z')
ch = 'z';
else if('A' <= s[i] && s[i] <= 'Z')
ch = 'Z';
if('A' <= s[i] && s[i] <= 'Z' || 'a' <= s[i] && s[i] <= 'z')
s[i] = ch - (ch - s[i] + key) % 26;<span style="font-family: Arial, Helvetica, sans-serif;">//实现字母之间的循环移位</span>
}
}
int main(){
string s = "";
cout<<"请输入明文:"<<endl;
getline(cin, s, '\n');
int key = 0;
cout<<"请输入密钥:"; cin>>key;
encrypt(s, key);
cout<<"加密后的密文:"<<s<<endl;
decrypt(s, key);
cout<<"解密后的明文:"<<s<<endl;
return 0;
}