#include<iostream>
#include<string>
#include<vector>
#include<cctype>
#include<fstream>
#include<sstream>
using namespace std;
vector<string> EncryptedMessage;
vector<string> word;
vector<vector<string>> dic;
string encryption(const string message,int i) {
string m = message;
for (auto j = 0; j < m.length(); j++) {
if (isalpha(m[j])) {
if (isupper(m[j])) {
m[j] = (m[j] - 'A' + i) % 26 + 'A';
}
else {
m[j] = (m[j] - 'a' + i) % 26 + 'a';
}
}
}
//cout << message << endl;
return m;
}
string decryption(string m,int i) {
string c = m;
for (auto j = 0; j < m.length(); j++) {
if (isalpha(m[j])) {
if (isupper(m[j])) {
c[j] = (m[j] - 'A' + 26 - i) % 26 + 'A';
}
else {
c[j] = (m[j] - 'a' + 26 - i) % 26 + 'a';
}
}
}
return c;
}
void readFile() {
string path = "《英汉汉英词典》.txt";
fstream file;
string ReadMessage;
file.open(path);
string s;
int count = 0;
if (file.is_open()) {
cout << "文件已打开" << endl;
while (getline(file, s))
{
int tt = tolower(s[0]) - 'a';
for (auto i = 0; i < s.length(); i++) {
if (isspace(s[i])) {
int index = i;
s = s.substr(0, index);
s[0] = tolower(s[0]);
word.push_back(s);
//cout << s << " " << s.length() << endl;
/*if (tt != s[0] - 'a') {
dic.push_back(word);
word.clear();
word.push_back(s);
count++;
}
else {
word.push_back(s);
count++;
}*/
//cout << s << endl;
}
}
}
/* cout << count << endl;*/
}
}
vector<string> splitWord(string m) {
vector<string> vec;
int index1 = 0, index2;
string word;
for (auto i = 0; i < m.length(); i++) {
if (m[i] == ' '||ispunct(m[i])||i==m.length()-1) {
if (i == m.length() - 1) {
index2 = i + 1;
}
else {
index2 = i;
}
word = m.substr(index1, index2 - index1);
index1 = index2+1;
word[0] = tolower(word[0]);
vec.push_back(word);
}
}
return vec;
}
int searchWord(string w) {
for (auto i = 0; i < word.size(); i++) {
if (w == word[i]) {
return 1;
}
}
return 0;
}
double getRate(string m) {
double count = 0.0;
vector<string> vec = splitWord(m);
for (auto i = 0; i < vec.size(); i++) {
//cout << vec[i] << endl;
if (searchWord(vec[i])) {
count++;
}
}
double rate = count / vec.size();
return rate;
}
int main() {
readFile();
double rate = 0;
string correctMessage;
string message = "Liu Weifu, meet me at the party"; //明文
int key = 5;
string m = encryption(message, key);
cout <<"密文 "<< m << endl;
for (auto i = 1; i < 26; i++) {
EncryptedMessage.push_back(decryption(m, i));
}
for (auto k = 0; k < EncryptedMessage.size(); k++) {
cout << "key = " << k+1 << " ";
cout << EncryptedMessage[k] << " ";
cout << getRate(EncryptedMessage[k]) << endl;
if (rate < getRate(EncryptedMessage[k])) {
rate = getRate(EncryptedMessage[k]);
correctMessage = EncryptedMessage[k];
}
}
cout << "明文为:" << correctMessage << endl;
system("pause");
return 0;
}
物联网安全技术——凯撒密码
最新推荐文章于 2025-05-13 10:30:27 发布