forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vigenere.java
61 lines (50 loc) · 1.55 KB
/
Vigenere.java
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
package ciphers;
/**
* A Java implementation of Vigenere Cipher.
*
* @author straiffix
*/
public class Vigenere {
public static String encrypt(final String message, final String key) {
String result = "";
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
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');
}
} else {
result += c;
}
j = ++j % key.length();
}
return result;
}
public static String decrypt(final String message, final String key) {
String result = "";
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
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 {
result += c;
}
j = ++j % key.length();
}
return result;
}
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));
}
}