Saturday, July 27, 2013

Simple statistical Attacks

//simple statistical Attacks
#include <iostream>
#include <cstdio>
#include <cctype>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;

map <char, int> mp;
map <char, int>::iterator it;

int main()
{
    string plainText, cipherText;
    int key;
    char secret;
    //freopen("input.txt","r",stdin);
    while(cin>>cipherText){
        int len = cipherText.size();

        for(int i=0; i<len; i++){
            mp[tolower(cipherText[i])]++;
        }

        int mx = 0;
        for(it = mp.begin(); it != mp.end(); it++){
            if((*it).second > mx) {
                mx = (*it).second;
                secret = (*it).first;
            }
        }
        key = abs((secret - 'a') - 4);
        cout<<"key: "<<key<<endl;

        //decrption
        plainText = "";
        for(int i=0; i<len; i++){
            int x = (cipherText[i] - 'A' - key) % 26;
            if(x<0) x += 26;
            plainText += (x + 'a');
        }
        cout<<"Plain Text: "<<plainText<<endl;
        //clearing
        mp.clear();
    }
    return 0;
}

No comments:

Post a Comment