//playfair_cipher
#include <iostream>
#include <string>
#include <cstdio>
#include <cctype>
#include <map>
#include <utility>
using namespace std;
#define siz 5
map <char, int> mp;
pair<int, int> p1;
pair<int, int> p2;
map < char, pair<int, int> > pa;
char a[siz][siz], res[siz][siz];
string as="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
bool ischar(char c){
if((c>='a' && c<='z') || (c>='A' && c<='Z'))
return true;
return false;
}
int main()
{
string key, message, msg;
//freopen("input.txt", "r", stdin);
while(getline(cin, key)){
int k = 0, l = 0;
int len = key.size();
for(int i=0;i<len;i++){
if(ischar(key[i])) {
if(mp[toupper(key[i])] == 0) {
a[k][l] = toupper(key[i]);
pa.insert(make_pair(toupper(key[i]), make_pair(k, l)));
mp[toupper(key[i])] = 1;
l++;
}
if(l==5) {
k++;
l = 0;
}
}
}
//mp['J'] = 1;
for(int i=0; i<as.size();i++){
if((toupper(as[i])=='I'||toupper(as[i])=='J') && (mp['I'] == 1||mp['J'] == 1))
continue;
if(mp[toupper(as[i])] == 1)
continue;
else {
a[k][l] = toupper(as[i]);
pa.insert(make_pair(toupper(as[i]), make_pair(k, l)));
l++;
}
if(l==5) {
k++;
l = 0;
}
}
//printing the grid
for(int i=0; i<5; i++) {
for(int j=0; j<5; j++) {
if(j) cout<< " ";
cout << a[i][j];
res[i][j]='0';
}
puts("");
}
//get the message
getline(cin, msg);
cout<<msg<<endl;
for(int i=0; i<msg.size(); i++)
if(ischar(msg[i]))
message += msg[i];
for(int i=0; i<message.size()-1; i++) {
char x,y;
if(message[i] != message[i+1]) {
x = toupper(message[i]);
y = toupper(message[i+1]);
p1 = pa.find(x)->second;
p2 = pa.find(y)->second;
i += 1;
} else {
x = toupper(message[i]);
y = 'X';
p1 = pa.find(x)->second;
p2 = pa.find(y)->second;
}
//columns are same
if(p1.second == p2.second) {
if(p1.first+1 < 5)
cout << a[p1.first + 1][p1.second];
else
cout << a[0][p1.second];
if(p2.first+1 < 5)
cout << a[p2.first + 1][p2.second];
else
cout << a[0][p2.second];
} else if(p1.first == p2.first) { //rows are same
if(p1.second+1 < 5)
cout << a[p1.first][p1.second + 1];
else
cout << a[p1.first][0];
if(p2.second+1 < 5)
cout << a[p2.first][p2.second + 1];
else
cout << a[p2.first][0];
} else {
cout << a[p1.first][p2.second]
<< a[p2.first][p1.second];
}
printf(" ");
}
//clearing
mp.clear();
}
return 0;
}
Saturday, August 24, 2013
Playfair Cipher Encryption in C++
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment