-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubstitutionCipher.java
More file actions
49 lines (41 loc) · 1.72 KB
/
SubstitutionCipher.java
File metadata and controls
49 lines (41 loc) · 1.72 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
import java.util.Scanner;
public class SubstitutionCipher {
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Example substitution key
String key = "QWERTYUIOPLKJHGFDSAZXCVBNM";
System.out.println("Enter text to encrypt:");
String plaintext = scanner.nextLine().toUpperCase();
String encryptedText = encrypt(plaintext, key);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
}
// Method to encrypt using substitution cipher
public static String encrypt(String plaintext, String key) {
StringBuilder encrypted = new StringBuilder();
for (char c : plaintext.toCharArray()) {
if (Character.isLetter(c)) {
int index = ALPHABET.indexOf(c);
encrypted.append(key.charAt(index));
} else {
encrypted.append(c); // Non-alphabetic characters remain unchanged
}
}
return encrypted.toString();
}
// Method to decrypt using substitution cipher
public static String decrypt(String ciphertext, String key) {
StringBuilder decrypted = new StringBuilder();
for (char c : ciphertext.toCharArray()) {
if (Character.isLetter(c)) {
int index = key.indexOf(c);
decrypted.append(ALPHABET.charAt(index));
} else {
decrypted.append(c); // Non-alphabetic characters remain unchanged
}
}
return decrypted.toString();
}
}