In: Computer Science
This problem needs to be solved with source code. I need a C++ program that will help me solve this question. I need it in C++, please. Writing with comments so it maybe cleared.
1.2. We received the following ciphertext which was encoded with a shift cipher:
xultpaajcxitltlxaarpjhtiwtgxktghidhipxciwtvgtpilpit ghlxiwiwtxgqadds.
1. Perform an attack against the cipher based on a letter frequency
count: How many letters do you have to identify through a frequency
count to recover the key? What is the cleartext?
#include <bits/stdc++.h>
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
string ciphertext = "xultpaajcxitltlxaarpjhtiwtgxktghidhipxciwtvgtpilpit ghlxiwiwtxgqadds";
// A string that has the alphabet in the decreasing order of frequency.
string alphafreq = "etaoinsrhdlucmfywgpbvkxqjz";
string cleartext;
// freq[] will store the frequency of each alphabetic character in the ciphertext
int freq[26] = {0}, i, j, most_freq, key;
char choice;
cout << "Ciphertext : " << ciphertext << '\n';
// Calculate the frequency of alphabet in the ciphertext
for(i = 0; i < ciphertext.length(); i++)
if(ciphertext[i] >= 97 && ciphertext[i] <= 122)
freq[ciphertext[i] - 97]++;
// Find the most frequent alphabet in the ciphertext
most_freq = 0;
for(i = 1; i < 26; i++)
if(freq[i] >= freq[most_freq])
most_freq = i;
/* Decode the ciphertext by substituting the most common alphabet
* in the ciphertext by the alphabet from alphafreq, one by one
*/
for(j = 0; j < 26; j++) {
key = most_freq + 97 - (int)alphafreq[j];
for(i = 0; i < ciphertext.length(); i++) {
if(ciphertext[i] >= 97 && ciphertext[i] <= 122)
if(ciphertext[i] + key >= 97 && ciphertext[i] + key <= 122)
cleartext.push_back(ciphertext[i] + key);
else if(ciphertext[i] + key > 122)
cleartext.push_back(ciphertext[i] + key - 26);
else
cleartext.push_back(ciphertext[i] + key + 26);
else
cleartext.push_back(' ');
}
/* If the user thinks the code has been decoded, he/she can quit,
* or else, retry with the next key.
*/
cout << "\nTry " << j+1 << ". Using key " << key << '\n';
cout << "Decoded text : " << cleartext << '\n';
cout << "Enter 'n' to try the next key, any other character to end.\n";
cin >> choice;
if(choice != 'n')
break;
cleartext.clear();
}
// If cleartext is empty, user didn't accept the result for any key
if(cleartext.empty())
cout << "Unable to decode.\n";
else
cout << "\nCleartext : "<< cleartext << '\n';
return(0);
}
OUTPUT: