-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoCh7App.java
More file actions
63 lines (49 loc) · 1.5 KB
/
CryptoCh7App.java
File metadata and controls
63 lines (49 loc) · 1.5 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
57
58
59
60
61
62
63
package gr.aueb.cf.ch10.projects;
public class CryptoCh7App {
public static void main(String[] args) {
String s = "JULIUS CAESAR";
final int KEY = 3;
String encrypted = encrypt(s, KEY);
System.out.println(encrypted);
String decrypted = decrypt(encrypted, KEY);
System.out.println(decrypted);
}
public static String encrypt(String s, int key) {
StringBuilder encrypted = new StringBuilder();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch)) {
encrypted.append(cipher(ch, key));
} else {
encrypted.append(ch);
}
}
return encrypted.toString();
}
public static String decrypt(String s, int key) {
StringBuilder decrypted = new StringBuilder();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch)) {
decrypted.append(decipher(ch, key));
} else {
decrypted.append(ch);
}
}
return decrypted.toString();
}
public static char cipher(char ch, int key) {
int m, c;
m = ch - 65;
c = (m + key) % 26;
return (char) + (c + 65);
}
public static char decipher(int ch, int key) {
int m, c;
c = ch - 65;
m = ((ch - key) + 26) % 26;
return (char) (m + 65);
}
}