-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayfairCipher.java
More file actions
89 lines (88 loc) · 2.33 KB
/
playfairCipher.java
File metadata and controls
89 lines (88 loc) · 2.33 KB
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
79
80
81
82
83
84
85
86
87
88
89
import java.awt.Point;
class playfairCipher {
private static char[][]
charTable; private static Point[]
positions;
private static String prepareText(String s, boolean chgJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTbl(String key, boolean chgJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
chgJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++)
{ char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] =
c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String codec(StringBuilder txt, int dir) {
int len = txt.length();
for (int i = 0; i < len; i += 2)
{ char a = txt.charAt(i);
char b = txt.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b -
'A'].y; int col1 = positions[a -
'A'].x; int col2 = positions[b -
'A'].x; if (row1 == row2) {
col1 = (col1 + dir) %
5; col2 = (col2 + dir)
% 5;
} else if (col1 == col2) {
row1 = (row1 + dir) %
5; row2 = (row2 + dir)
% 5;
} else {
int tmp =
col1; col1 =
col2; col2 =
tmp;
}
txt.setCharAt(i, charTable[row1][col1]);
txt.setCharAt(i + 1, charTable[row2]
[col2]);
}
return txt.toString();
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1) {
sb.append(sb.length() % 2 == 1 ? 'X' : "");
} else if (sb.charAt(i) == sb.charAt(i + 1))
{ sb.insert(i + 1, 'X');
}
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s),
4);
}
public static void main(String[] args) throws java.lang.Exception {
String key = "CSE";
String txt = "Security Lab"; /* make sure string length is even */ /* change J
to I */
boolean chgJtoI = true;
createTbl(key, chgJtoI);
String enc = encode(prepareText(txt, chgJtoI));
System.out.println("Simulating Playfair Cipher\n---------------------");
System.out.println("Input Message : " + txt);
System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc));
}
}
OUTPUT:
Simulating Playfair Cipher
Input Message : Security Lab
Encrypted Message :
EABPUGYANSEZ Decrypted Message
: SECURITYLABX