public class Cipher {
public static char[] cipherKey;
public static char[] decipherKey;
Cipher(int shift) {
cipherKey = new char[256];
decipherKey = new char[256];
int i = 0;
int j = 0;
for (i = 0; i<=255; i++) {
cipherKey[i] = (char)i;
decipherKey[i] = (char)i;
}
for (i = ((int)'a'); i<=(int)'z'-shift; i++) {
cipherKey[i] = (char) ((int)cipherKey[i] + shift);
decipherKey[(char)cipherKey[i]] = (char)i;
}
j = 0;
for (i = ((int)'z'-shift+1); j < shift; j++) {
cipherKey[i] = (char) ((int)'a' + j);
decipherKey[(char)cipherKey[i]] = (char) ((int)i);
i++;
}
for (i = (int)'A'; i<=(int)'Z'-shift; i++) {
cipherKey[i] = (char) ((int)cipherKey[i] + shift);
decipherKey[(char)cipherKey[i]] = (char)i;
}
j = 0;
for (i = ((int)'Z'-shift+1); j < shift; j++) {
cipherKey[i] = (char) ((int)'A' + j);
decipherKey[(char)cipherKey[i]] = (char) ((int)i);
i++;
}
// for (i=0; i<=255; i++)
// System.out.printf("i = %d old char = %c new char = %c decipher char = %c\n",
// i,(char)i,cipherKey[i], decipherKey[i]);
}
public String cypher(String ins) {
String s = "";
for (int i = 0; i < ins.length(); i++)
s = s + cipherKey[(int)ins.charAt(i)];
return s;
}
public String decypher(String ins) {
String s = "";
for (int i = 0; i < ins.length(); i++)
s = s + decipherKey[(int)ins.charAt(i)];
return s;
}
public static String caesarEncipher (String input, int shift) {
Cipher c = new Cipher(shift);
return c.cypher(input);
}
public static String caesarDecipher (String input, int shift) {
Cipher c = new Cipher(shift);
return c.decypher(input);
}
public static void main(String[] args) {
String[] tests = {"Hello","hello", "This is my job", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"qwertyuioplkjhgfdsazxcvbnm"};
Cipher c = new Cipher(5);
System.out.println("Test cypher and decypher (shift = 5)");
for (String s : tests) {
String q = s;
System.out.printf("\tCypher text of (%s) = %s\n", s, c.cypher(s));
q = c.cypher(s);
System.out.printf("\tDecypher text of (%s) = %s\n\n", q, c.decypher(q));
}
System.out.println("\nTest caesarEncipher and caesarDecipher (2)");
for (String s : tests) {
String q = s;
System.out.printf("\tCypher text of (%s) = %s\n",s,
c.caesarEncipher(s, 2));
q = c.caesarEncipher(s, 2);
System.out.printf("\tCypher text of (%s) = %s\n\n",q,
c.caesarDecipher(q, 2));
}
} // main
} // cipher
|