思路:将加密和解密的过程转化为ASCII编码的运算
#include<iostream>
using namespace std;
void showMenu() { //菜单
cout << "------维吉尼亚密码加密解密------" << endl;
cout << "1.加密" << endl;
cout << "2.解密" << endl;
cout << "3.退出" << endl;
cout << "请输入需要进行的操作:" << endl;
}
string StoB(string Key) { //将Key全部转换成大写字母,方便后续进行ASCII编码的计算
for (int i = 0;i<Key.length();i++) {
if (Key[i] >= 'a' && Key[i] <= 'z') Key[i] = char(Key[i] + 'A' - 'a');
}
return Key;
}
void encrypt(string EnMessage,string Key) { //加密
int len_K = Key.length();
int index = 0;
cout << "加密后为:";
for (auto n : EnMessage) {
if (index > len_K-1) index = 0; //通过ASCII编码的运算实现加密操作
if (n >= 'A' && n <= 'Z') { //大写字母
if ((n + Key[index] - 'A') <= 'Z') cout << char(n + Key[index] - 'A');
else cout << char('A' + (n + Key[index] - 'A' - 'Z') - 1);
}
else if (n >= 'a' && n <= 'z') { //小写字母
if ((n + (Key[index] - 'A' + 'a') - 'a') <= 'z') cout << char(n + (Key[index] - 'A' + 'a') - 'a');
else cout << char('a' + (n + (Key[index] - 'A' + 'a') - 'a' - 'z') - 1);
}
else cout << n; //其他字符直接输出
index++;
}
cout << endl;
}
void decrypt(string DeMessage,string Key) { //解密
int len_K = Key.length();
int index = 0;
cout << "解密后为:";
for (auto n: DeMessage) {
if (index > len_K-1) index = 0; //通过ASCII编码的运算实现解密操作
if (n >= 'A' && n <= 'Z') { //大写字母
if ((n - Key[index] + 'A') >= 'A') cout << char(n - Key[index] + 'A');
else cout << char('Z' - ('A' - (n - Key[index] + 'A')) + 1);
}
else if (n >= 'a' && n <= 'z') { //小写字母
if ((n - (Key[index] - 'A' + 'a') + 'a') >= 'a') cout << char(n - (Key[index] - 'A' + 'a') + 'a');
else cout << char('z' - ('a' - (n - (Key[index] - 'A' + 'a') + 'a')) + 1);
}
else cout << n; //其他字符直接输出
index++;
}
cout << endl;
}
int main()
{
int select;
string EnMessage,DeMessage,EnKey,DeKey;
while (1) {
showMenu();
cin >> select;
switch (select) {
case 1: //加密
cout << "请输入加密的密钥:" << endl;
cin >> EnKey;
cout << "请输入需要加密的消息:" << endl;
cin >> EnMessage;
encrypt(EnMessage, StoB(EnKey));
break;
case 2: //解密
cout << "请输入需要解密的消息:" << endl;
cin >> DeMessage;
cout << "请输入密钥:" << endl;
cin >> DeKey;
decrypt(DeMessage,StoB(DeKey));
break;
case 3: //退出
cout << "欢迎下次使用!" << endl;
return 0; //结束程序
default: //其他情况
cout << "输入错误!请重新输入" << endl;
break;
}
}
}
此程序能保证密文和明文大小写保持一致,且若文本中出现非字母字符会原样保留。具有较强的健壮性。
若有其他bug,欢迎在评论区指正
标签:case,加密,cout,解密,C++,&&,维吉尼亚,ASCII From: https://blog.csdn.net/Young_iM/article/details/144397163