2018-04-14 07:39:08 +08:00
|
|
|
package ciphers;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A Java implementation of Vigenere Cipher.
|
|
|
|
* @author straiffix
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
public class Vigenere {
|
|
|
|
|
2018-04-15 16:45:31 +08:00
|
|
|
public static String encrypt(final String message, final String key)
|
2018-04-14 07:39:08 +08:00
|
|
|
{
|
|
|
|
|
|
|
|
String result = "";
|
|
|
|
|
2018-04-15 16:45:31 +08:00
|
|
|
for (int i = 0, j = 0; i < message.length(); i++) {
|
2018-04-14 07:39:08 +08:00
|
|
|
char c = message.charAt(i);
|
2018-04-15 16:45:31 +08:00
|
|
|
if (Character.isLetter(c)){
|
|
|
|
if(Character.isUpperCase(c)) {
|
|
|
|
result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A');
|
|
|
|
|
|
|
|
} else {
|
|
|
|
result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a');
|
|
|
|
|
|
|
|
}
|
2018-04-14 07:39:08 +08:00
|
|
|
} else {
|
|
|
|
result+=c;
|
|
|
|
}
|
2018-04-15 16:45:31 +08:00
|
|
|
j = ++j % key.length();
|
2018-04-14 07:39:08 +08:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2018-04-15 16:45:31 +08:00
|
|
|
public static String decrypt( final String message, final String key)
|
2018-04-14 07:39:08 +08:00
|
|
|
{
|
|
|
|
String result ="";
|
|
|
|
|
|
|
|
for(int i = 0, j = 0; i < message.length(); i++){
|
|
|
|
|
|
|
|
char c = message.charAt(i);
|
2018-04-15 16:45:31 +08:00
|
|
|
if (Character.isLetter(c)){
|
|
|
|
if(Character.isUpperCase(c)) {
|
|
|
|
result += ((char)('Z'-(25-(c-key.toUpperCase().charAt(j)))%26));
|
|
|
|
|
|
|
|
} else {
|
|
|
|
result += ((char)('z'-(25-(c-key.toLowerCase().charAt(j)))%26));
|
|
|
|
|
|
|
|
}
|
|
|
|
} else {
|
2018-04-14 07:39:08 +08:00
|
|
|
result+=c;
|
|
|
|
}
|
2018-04-15 16:45:31 +08:00
|
|
|
|
2018-04-14 07:39:08 +08:00
|
|
|
j = ++j % key.length();
|
2018-04-15 16:45:31 +08:00
|
|
|
|
2018-04-14 07:39:08 +08:00
|
|
|
}
|
|
|
|
return result;
|
2018-04-15 16:45:31 +08:00
|
|
|
}
|
2018-04-14 07:39:08 +08:00
|
|
|
public static void main (String [] args){
|
|
|
|
String text="Hello World!";
|
|
|
|
String key="itsakey";
|
|
|
|
System.out.println(text);
|
|
|
|
String ciphertext=encrypt(text, key);
|
|
|
|
System.out.println(ciphertext);
|
|
|
|
System.out.println(decrypt(ciphertext, key));
|
|
|
|
|
|
|
|
}
|
2018-04-15 16:45:31 +08:00
|
|
|
}
|