-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaeser.java
51 lines (47 loc) · 1.22 KB
/
caeser.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
import java.util.*;
class Main{
private static class CaeserCipher{
private String preprocess(String text){
return (text.toLowerCase()).replaceAll("\\s+","");
}
private String encrypt(String plainText, int key){
plainText = preprocess(plainText);
int n = plainText.length();
String cipherText = "";
for(int i = 0; i < n; i++){
int flag = 0;
char temp = plainText.charAt(i);
temp += key;
if(temp > 'z')
temp -= 26;
cipherText += temp+"";
}
return cipherText;
}
private String decrypt(String cipherText, int key){
int n = cipherText.length();
String plainText = "";
for(int i = 0; i < n; i++){
int flag = 0;
char temp = cipherText.charAt(i);
temp -= key;
if(temp < 'a')
temp += 26;
plainText += temp+"";
}
return plainText;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.printf("Enter plainText: ");
String text = in.nextLine();
System.out.printf("Enter key: ");
int key = in.nextInt();
CaeserCipher cipher = new CaeserCipher();
text = cipher.encrypt(text, key);
System.out.printf("cipherText: "+text+"\n");
text = cipher.decrypt(text, key);
System.out.printf("plainText: "+text);
}
}