一、rot5
rot移位密码是一种特殊形式的凯撒密码,本质上是一种循环移位密码。其步长为总字符数的一半,也就是其加密和解密是一样的。对密文再进行一次加密就可以恢复明文。
rot5的字符集是0-9,而步长是5。rot5只对数字处理,而其他字符保持不变。例如:
明文:1278
密文:6723
其c++实现如下:
#include<iostream>
#include<cctype>
using namespace std;
string rot5(string str){
for(int i=0;i<str.size();i++){
if(isdigit(str[i])){
str[i]-='0';
str[i]=(str[i]+5)%10+'0';
}
}
return str;
}
int main(){
string mess;
string cipher;
cout<<"Please input the message:"<<endl;
cin>>mess;
cout<<"The ciphertext is:"<<endl;
cipher=rot5(mess);
cout<<cipher<<endl;
cout<<"encrypt again:"<<endl;
cout<<rot5(cipher)<<endl;
return 0;
}
二、rot13
rot13的字符集是26个英文字母,其移位步长为13,而其他的字符保持不变。
其实现代码如下:
#include<iostream>
#include<cctype>
using namespace std;
string rot13(string str){
for(int i=0;i<str.size();i++){
if(islower(str[i])){
str[i]-='a';
str[i]=(str[i]+13)%26+'a';
}else if(isupper(str[i])){
str[i]-='A';
str[i]=(str[i]+13)%26+'A';
}
}
return str;
}
int main(){
string mess;
string cipher;
cout<<"Please input the message:"<<endl;
cin>>mess;
cout<<"The ciphertext is:"<<endl;
cipher=rot13(mess);
cout<<cipher<<endl;
cout<<"encrypt again:"<<endl;
cout<<rot13(cipher)<<endl;
return 0;
}
三、rot18
rot18是指数字用rot5加密,而字母用rot13加密,其他字符保持不变。
其c++实现代码如下:
#include<iostream>
#include<cctype>
using namespace std;
string rot18(string str){
for(int i=0;i<str.size();i++){
if(islower(str[i])){
str[i]-='a';
str[i]=(str[i]+13)%26+'a';
}else if(isupper(str[i])){
str[i]-='A';
str[i]=(str[i]+13)%26+'A';
}else if(isdigit(str[i])){
str[i]-='0';
str[i]=(str[i]+5)%10+'0';
}
}
return str;
}
int main(){
string mess;
string cipher;
cout<<"Please input the message:"<<endl;
cin>>mess;
cout<<"The ciphertext is:"<<endl;
cipher=rot18(mess);
cout<<cipher<<endl;
cout<<"encrypt again:"<<endl;
cout<<rot18(cipher)<<endl;
return 0;
}
四、rot47
rot47的字符集是ASCII码为33~126(包括126)的94个字符,步长为47.
其c++实现如下:
#include<iostream>
using namespace std;
string rot47(string str){
for(int i=0;i<str.size();i++){
if(str[i]<127 and str[i]>32){
str[i]-=33;
str[i]=(str[i]+47)%94+33;
}
}
return str;
}
int main(){
string mess;
string cipher;
cout<<"Please input the message:"<<endl;
cin>>mess;
cout<<"The ciphertext is:"<<endl;
cipher=rot47(mess);
cout<<cipher<<endl;
cout<<"encrypt again:"<<endl;
cout<<rot47(cipher)<<endl;
return 0;
}