-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBeaufortCipher.java
More file actions
56 lines (41 loc) · 1.72 KB
/
BeaufortCipher.java
File metadata and controls
56 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
50
51
52
53
54
55
56
import java.util.Scanner;
public class BeaufortCipher {
public static String beaufortEncrypt(String plainText, String key) {
StringBuilder cipherText = new StringBuilder();
int keyIndex = 0;
for (char plainChar : plainText.toCharArray()) {
if (Character.isLetter(plainChar)) {
char keyChar = Character.toUpperCase(key.charAt(keyIndex));
char plainCharUpper = Character.toUpperCase(plainChar);
int shift = (keyChar - plainCharUpper + 26) % 26;
char encryptedChar = (char) ('A' + shift);
if (Character.isLowerCase(plainChar)) {
cipherText.append(Character.toLowerCase(encryptedChar));
} else {
cipherText.append(encryptedChar);
}
keyIndex = (keyIndex + 1) % key.length();
} else {
cipherText.append(plainChar);
}
}
return cipherText.toString();
}
public static String beaufortDecrypt(String cipherText, String key) {
return beaufortEncrypt(cipherText, key);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter plain text: ");
String plainText = scanner.nextLine();
System.out.print("Enter secret key: ");
String key = scanner.nextLine();
// Encryption
String cipherText = beaufortEncrypt(plainText, key);
System.out.println("Encrypted text: " + cipherText);
// Decryption
String decryptedText = beaufortDecrypt(cipherText, key);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
}