Playfair cipher: Difference between revisions

Content added Content deleted
Line 337: Line 337:


private static String decode(String out) {
private static String decode(String out) {
return codec(new StringBuilder(out), 4);
return c(new StringBuilder(out), 4);
}
}


private static String codec(StringBuilder txt, int dir) {
private static String c(StringBuilder string, int direction) {
int len = txt.length();
int len = string.length();
for (int i = 0; i < len; i += 2) {
for (int i = 0; i < len; i += 2) {
char a = txt.charAt(i);
char a = txt.charAt(i);
char b = txt.charAt(i + 1);
char b = txt.charAt(i + 1);


int r1 = positions[a - 'A'].y;
int rowOne = positions[a - 'A'].y;
int r2 = positions[b - 'A'].y;
int rowTwo = positions[b - 'A'].y;
int c1 = positions[a - 'A'].x;
int columnOne = positions[a - 'A'].x;
int c2 = positions[b - 'A'].x;
int columnTwo = positions[b - 'A'].x;


if (r1 == r2) {
if (rowOne == rowTwo) {
c1 = (c1 + dir) % 5;
columnOne = (columnOne + direction) % 5;
c2 = (c2 + dir) % 5;
columnTwo = (columnTwo + direction) % 5;


} else if (c1 == c2) {
} else if (columnOne == c2) {
r1 = (r1 + dir) % 5;
rowOne = (rowOne + direction) % 5;
r2 = (r2 + dir) % 5;
rowTwo = (rowTwo + direction) % 5;


} else {
} else {
int tmp = c1;
int tmp = columnOne;
c1 = c2;
columnOne = columnTwo;
c2 = tmp;
columnTwo = tmp;
}
}


txt.setCharAt(i, charTable[r1][c1]);
string.setCharAt(i, charTable[rowOne][columnOne]);
txt.setCharAt(i + 1, charTable[r2][c2]);
string.setCharAt(i + 1, charTable[rowTwo][columnTwo]);
}
}
return txt.toString();
return string.toString();
}
}
}</lang>
}</lang>