-
Notifications
You must be signed in to change notification settings - Fork 92
/
CeaserCipher.java
104 lines (94 loc) · 3.77 KB
/
CeaserCipher.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package Programs;
import java.util.Scanner;
public class CeaserCipher {
public static void main(String[] args) {
System.out.println("""
--------------------------------
CEASER CIPHER ENCRYPT/ DECRYPT
--------------------------------
""");
Scanner sc = new Scanner(System.in);
System.out.println("Encrypt or Decrypt:\n 1- Encryption\n 2- Decryption");
int type = sc.nextInt();
for (int j = 1; j > 0; j++) {
if (type == 1) {
ceaserCipherEncryption();
break;
} else if (type == 2) {
ceaserCipherDecryption();
break;
} else {
System.out.print("Please enter a valid number (1 or 2): ");
type = sc.nextInt();
}
}
}
public static void ceaserCipherEncryption() {
Scanner textInput = new Scanner(System.in);
System.out.print("PlainText: ");
String textToEncrypt = textInput.nextLine();
System.out.print("shifting key: ");
int keyToUse = textInput.nextInt();
String cipher = "";
for (int i = 0; true; i++) {
if (keyToUse > 50 && keyToUse <= 0) {
System.out.print("Please Enter key value <= 50: ");
keyToUse = textInput.nextInt();
} else {
for (int j = 0; j < textToEncrypt.length(); j++) {
char temp = textToEncrypt.charAt(j);
if (temp >= 'A' && temp <= 'Z') {
temp = (char) (temp + keyToUse);
if (temp > 'Z') { // go back to A in Ascii
temp = (char) (temp + 'A' - 'Z' - 1);
}
cipher += temp;
} else if (temp >= 'a' && temp <= 'z') {
temp = (char) (temp + keyToUse);
if (temp > 'z') { // go back to a in Ascii
temp = (char) (temp + 'a' - 'z' - 1);
}
cipher += temp;
} else
cipher += temp;
}
}
System.out.println("Enrypted text is: " + cipher);
break;
}
}
public static void ceaserCipherDecryption() {
Scanner textInput = new Scanner(System.in);
System.out.print("Encrypted Text: ");
String textToEncrypt = textInput.nextLine();
System.out.print("shifting key: ");
int keyToUse = textInput.nextInt();
String cipher = "";
for (int i = 0; true; i++) {
if (keyToUse > 50 && keyToUse <= 0) {
System.out.print("Please Enter key value <= 50: ");
keyToUse = textInput.nextInt();
} else {
for (int j = 0; j < textToEncrypt.length(); j++) {
char temp = textToEncrypt.charAt(j);
if (temp >= 'A' && temp <= 'Z') {
temp = (char) (temp - keyToUse);
if (temp < 'A') { // go back to A in Ascii
temp = (char) (temp - 'A' + 'Z' + 1);
}
cipher += temp;
} else if (temp >= 'a' && temp <= 'z') {
temp = (char) (temp - keyToUse);
if (temp < 'a') { // go back to a in Ascii
temp = (char) (temp - 'a' + 'z' + 1);
}
cipher += temp;
} else
cipher += temp;
}
}
System.out.println("Decrypted text is: " + cipher);
break;
}
}
}