单表置换加密即让原符号与新符号一一对应,进而对用原符号组成的符号串进行加密。
加密
//加密int encrypt(string& sentence){int location;string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //对应的置换单表,可进行修改for (int i = 0; i < sentence.length(); i++){location = alphabet.find_first_of(sentence[i]);if (location != -1) //非英文字母不加密{sentence[i] = key[location];}}return 1;}
解密
//解密int decipher(string& sentence){int location;string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for (int i = 0; i < sentence.length(); i++){location = key.find_first_of(sentence[i]);if (location != -1){sentence[i] = alphabet[location];}}return 1;}
完整代码
#include<bits/stdc++.h>using namespace std;//单表代替密码//find_first_of()//在母串上从指定位置开始查找,//如果遇到的字符与目标串中任意字符相同,则查找成功,返回该字符的位置。//若没有,返回-1//加密int encrypt(string& sentence){int location;string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //对应的置换单表,可进行修改for (int i = 0; i < sentence.length(); i++){location = alphabet.find_first_of(sentence[i]);if (location != -1) //非英文字母不加密{sentence[i] = key[location];}}return 1;}//解密int decipher(string& sentence){int location;string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for (int i = 0; i < sentence.length(); i++){location = key.find_first_of(sentence[i]);if (location != -1){sentence[i] = alphabet[location];}}return 1;}int main(){string sentence;//cout << "请输入要加密的文字:" << endl;//getline(cin, sentence);sentence = " Time waits for no man !";encrypt(sentence);cout << "加密后" << endl;cout << sentence << endl;decipher(sentence);cout << "解密后" << endl;cout << sentence << endl;}
