forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVigenere.java
More file actions
78 lines (71 loc) · 2.35 KB
/
Vigenere.java
File metadata and controls
78 lines (71 loc) · 2.35 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
package com.thealgorithms.ciphers;
/**
* A Java implementation of Vigenere Cipher.
*
* @author straiffix
* @author beingmartinbmc
*/
public class Vigenere {
public static String encrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
result.append(
(char) (
(c + key.toUpperCase().charAt(j) - 2 * 'A') %
26 +
'A'
)
);
} else {
result.append(
(char) (
(c + key.toLowerCase().charAt(j) - 2 * 'a') %
26 +
'a'
)
);
}
} else {
result.append(c);
}
j = ++j % key.length();
}
return result.toString();
}
public static String decrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
result.append(
(char) (
'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26
)
);
} else {
result.append(
(char) (
'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26
)
);
}
} else {
result.append(c);
}
j = ++j % key.length();
}
return result.toString();
}
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));
}
}