Answer to Question #61878 in C++ for johhny

Question #61878
write an algorithm in c++ to attack caesar cipher ,knowing the plain text & the cipher text
1
Expert's answer
2016-09-16T09:24:03-0400
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
using std::ofstream;
#include <string>
using std::string;

bool is_equals(const string& a, const string& b)
{
unsigned int sz = a.size();
if (b.size() != sz)
return false;
for (unsigned int i = 0; i < sz; ++i)
if (tolower(a[i]) != tolower(b[i]))
return false;
return true;
}

void print_usage() {
cout << "Usage: <plaintext> <ciphertext>" << endl;
}

int get_encryption_key(string plain_text, string cipher_text) {
const string ALPHABET = "abcdefghijklmnopqrstuvwxyz";
const int SHIFT_VALUE = 1;

for(int key = 0; key < ALPHABET.size(); ++key) {
if(is_equals(plain_text, cipher_text)) return key;
// Shift ciphertext
for(size_t i = 0; i < cipher_text.size(); ++i) {
char symb = tolower(cipher_text[i]);
long pos = ALPHABET.find(symb);
if(!isalpha(symb)) continue;
if(pos == string::npos) return -1;
char next_symb = ALPHABET[ (pos + SHIFT_VALUE) % ALPHABET.size() ];
cipher_text[i] = isupper(cipher_text[i]) ? toupper(next_symb) : next_symb;
}
}
return -1;
}


int main(int argc, char *argv[]) {

if(argc != 3) {
print_usage();
return 0;
}

ifstream plain_input(argv[1]);
ifstream cipher_input(argv[2]);

if(!plain_input.is_open()) {
cout << "Error open plaintext file" << endl;
return -1;
}

if(!cipher_input.is_open()) {
cout << "Error open ciphertext file" << endl;
return -1;
}

string plain_text = "", cipher_text;
while(!plain_input.eof()) plain_text += plain_input.get();
while(!cipher_input.eof()) cipher_text += cipher_input.get();

cout << "Encryption key: " << get_encryption_key(plain_text, cipher_text) << endl;

plain_input.close();
cipher_input.close();

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS