Sunday, August 25, 2013

Columnar Transposition Cipher Encryption in C++

//columnar_transposition
#include <iostream>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cctype>
#include <map>
using namespace std;
#define siz 100
char as[siz][siz];
int a[siz];
map <int, int> mp;
map <int, int>::iterator it;
int main()
{
    string plainText1, plainText, key, cipherText;
    freopen("input.txt", "r", stdin);
    while(getline(cin, plainText1) && getline(cin, key)) {

        cout << "Plain Text: " << plainText1 <<endl;
        cout << "Key: " << key <<endl;

        for(int i=0; i<key.size(); i++)
            mp[(key[i]-'A')] = i;

        for(int i=0; i<plainText1.size(); i++)
            if(isalpha(plainText1[i]))
                plainText += plainText1[i];

        int k = 0, row = 0;
        for(int i=0; ; i++){
            for(int j=0; j<key.size(); j++) {
                if(k >= plainText.size()) {
                    as[i][j] = rand()%26 + 'A';
                } else {
                    as[i][j] = plainText[k];
                }
                k++;
            }
            row++;
            if(k >= plainText.size()) break;
        }
        puts("Grid:");
        for(int i=0; i<row; i++){
            for(int j=0; j<key.size(); j++) {
                cout<<as[i][j]<<" ";
            }
            puts("");
        }


        for(it = mp.begin(); it != mp.end(); it++) {
            for(int i=0; i<row; i++){
                cipherText += as[i][(*it).second];
            }
            cipherText += " ";
        }

        cout<<"Cipher Text: "<<cipherText<<endl;
    }
    return 0;
}



No comments:

Post a Comment