-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCipher.java
41 lines (40 loc) · 1.45 KB
/
CaesarCipher.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
public class CaesarCipher{
protected char[] encoder = new char[26];
protected char[] decoder = new char[26];
public CaesarCipher(int rotation ){
for(int k=0; k<26; k++){
encoder[k] = (char)('A' + (k+rotation)%26);
decoder[k] = (char)('A' + (k-rotation + 26)%26);
}
}
public String encrypt(String message){
return transform(message, encoder);
}
public String decrypt(String secret){
return transform(secret, decoder);
}
private String transform(String original, char[] code){
char[] msg = original.toCharArray();
for(int k=0; k<msg.length; k++){
if(Character.isUpperCase(msg[k])){
int j = msg[k]-'A';
msg[k] = code[j];
}
}
return new String(msg);
}
public static void main(String[] args){
CaesarCipher cipher = new CaesarCipher(8);
System.out.println("Encryption code = "+ new String(cipher.encoder));
System.out.println("Decryption code = "+ new String(cipher.decoder));
String message = "My name is Rajendra Pancholi";
String coded = cipher.encrypt(message);
System.out.println("Secret: "+ coded);
String answer = cipher.decrypt(coded);
System.out.print("Message: "+answer);
System.out.print("print1");
System.out.print("print2");
System.out.print("print3");
System.out.print("print4");
}
}