-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.playfaircipher.cpp
78 lines (67 loc) · 2.29 KB
/
3.playfaircipher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<bits/stdc++.h>
using namespace std;
class Playfair{
string key;
int find_in_key(char a){
for(int i=0; i<25; i++){
if(a==key[i])
return i;
}
return -1;
}
pair<char, char> encipher_pair(char a, char b){
int a_id = find_in_key(a), b_id = find_in_key(b);
int x_a=a_id/5, y_a=a_id%5, x_b=b_id/5, y_b=b_id%5;
if(x_a == x_b)
return make_pair(key[x_a*5 + (y_a+1)%5], key[x_b*5 + (y_b+1)%5]);
if(y_a == y_b)
return make_pair(key[((x_a+1)%5)*5 + y_a], key[((x_b+1)%5)*5 + y_b]);
else
return make_pair(key[x_a*5 + y_b], key[x_b*5 + y_a]);
}
pair<char, char> decipher_pair(char a, char b){
int a_id = find_in_key(a), b_id = find_in_key(b);
int x_a=a_id/5, y_a=a_id%5, x_b=b_id/5, y_b=b_id%5;
if(x_a==x_b)
return make_pair(key[x_a*5 + (y_a-1)%5], key[x_b*5 + (y_b-1)%5]);
if(y_a == y_b)
return make_pair(key[((x_a-1)%5)*5 + y_a], key[((x_b-1)%5)*5 + y_b]);
else
return make_pair(key[x_a*5 + y_b], key[x_b*5 + y_a]);
}
public:
Playfair(string KEY){key = KEY;}
string encipher(string plainText){
if(plainText.length()%2 == 1)
plainText += "x";
string cipherText = plainText;
for(int i=0; i<plainText.length(); i+=2){
pair<char, char> t = encipher_pair(plainText[i], plainText[i+1]);
cipherText[i] = t.first;
cipherText[i+1] = t.second;
}
return cipherText;
}
string decipher(string cipherText){
if(cipherText.length()%2 == 1)
cipherText += "x";
string plainText = cipherText;
for(int i=0; i<cipherText.length(); i+=2){
pair<char,char> t = decipher_pair(cipherText[i], cipherText[i+1]);
plainText[i] = t.first;
plainText[i+1] = t.second;
}
return plainText;
}
};
int main(){
string key = "alonpzmihxvyrswukdfteqqcb";
Playfair p(key);
string plainText;
cout<<"Enter the plain text : ";
cin>>plainText;
cout<<"*******************************"<<endl;
cout<<"Encoded cipher text : "<< p.encipher(plainText) << endl;
cout<<"Deciphered plain text : "<< p.decipher(p.encipher(plainText)) << endl;
return 0;
}