- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathMonoAlphabetic.java
48 lines (40 loc) · 1.71 KB
/
MonoAlphabetic.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
packagecom.thealgorithms.ciphers;
publicfinalclassMonoAlphabetic {
privateMonoAlphabetic() {
thrownewUnsupportedOperationException("Utility class");
}
// Encryption method
publicstaticStringencrypt(Stringdata, Stringkey) {
if (!data.matches("[A-Z]+")) {
thrownewIllegalArgumentException("Input data contains invalid characters. Only uppercase A-Z are allowed.");
}
StringBuildersb = newStringBuilder();
// Encrypt each character
for (charc : data.toCharArray()) {
intidx = charToPos(c); // Get the index of the character
sb.append(key.charAt(idx)); // Map to the corresponding character in the key
}
returnsb.toString();
}
// Decryption method
publicstaticStringdecrypt(Stringdata, Stringkey) {
StringBuildersb = newStringBuilder();
// Decrypt each character
for (charc : data.toCharArray()) {
intidx = key.indexOf(c); // Find the index of the character in the key
if (idx == -1) {
thrownewIllegalArgumentException("Input data contains invalid characters.");
}
sb.append(posToChar(idx)); // Convert the index back to the original character
}
returnsb.toString();
}
// Helper method: Convert a character to its position in the alphabet
privatestaticintcharToPos(charc) {
returnc - 'A'; // Subtract 'A' to get position (0 for A, 1 for B, etc.)
}
// Helper method: Convert a position in the alphabet to a character
privatestaticcharposToChar(intpos) {
return (char) (pos + 'A'); // Add 'A' to convert position back to character
}
}