-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreeKeyCipher.java
42 lines (38 loc) · 1.52 KB
/
ThreeKeyCipher.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
import java.util.Scanner;
public class ThreeKeyCipher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String input = sc.nextLine();
String encryptedText = encrypt(input);
String decryptedText = decrypt(encryptedText);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decryptedText);
}
public static String encrypt(String input) {
StringBuilder newText = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (Character.isLetter(currentChar)) {
char base = Character.isLowerCase(currentChar) ? 'a' : 'A';
newText.append((char) (((currentChar - base + 3) % 26) + base));
} else {
newText.append(currentChar);
}
}
return newText.toString();
}
public static String decrypt(String input) {
StringBuilder newText = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (Character.isLetter(currentChar)) {
char base = Character.isLowerCase(currentChar) ? 'a' : 'A';
newText.append((char) (((currentChar - base - 3 + 26) % 26) + base));
} else {
newText.append(currentChar);
}
}
return newText.toString();
}
}