-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolyalphabeticCipher.java
More file actions
52 lines (47 loc) · 1.83 KB
/
PolyalphabeticCipher.java
File metadata and controls
52 lines (47 loc) · 1.83 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
import java.util.Scanner;
public class PolyalphabeticCipher {
public static String encrypt(String text, String key) {
StringBuilder encrypted = new StringBuilder();
int keyIndex = 0;
key = key.toLowerCase();
for (char ch : text.toCharArray()) {
if (Character.isAlphabetic(ch)) {
char base = Character.isUpperCase(ch) ? 'A' : 'a';
char keyChar = key.charAt(keyIndex % key.length());
encrypted.append((char) ((ch - base + (keyChar - 'a')) % 26 + base));
keyIndex++;
} else {
encrypted.append(ch);
}
}
return encrypted.toString();
}
public static String decrypt(String text, String key) {
StringBuilder decrypted = new StringBuilder();
int keyIndex = 0;
key = key.toLowerCase();
for (char ch : text.toCharArray()) {
if (Character.isAlphabetic(ch)) {
char base = Character.isUpperCase(ch) ? 'A' : 'a';
char keyChar = key.charAt(keyIndex % key.length());
decrypted.append((char) ((ch - base - (keyChar - 'a') + 26) % 26 + base));
keyIndex++;
} else {
decrypted.append(ch);
}
}
return decrypted.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the plaintext: ");
String text = scanner.nextLine();
System.out.print("Enter the key: ");
String key = scanner.nextLine();
String encrypted = encrypt(text, key);
System.out.println("Encrypted text: " + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("Decrypted text: " + decrypted);
scanner.close();
}
}