forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCipher.java
83 lines (72 loc) · 2.54 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
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
/**
* Caesar Cipher => Encryption: CipherText = (PlainText+Key)mod26
* => Decryption: PlainText = (CipherText-Key)mod26
*
* value of Key: 3
* Enter the message: hello world
* Encryption Message: KHOOR ZRUOG
* Decryption Message: HELLO WORLD
*/
import java.util.Scanner;
class Encrypt
{
int pVal, encryptFormula;
char encryptChar;
// CipherText = (PlainText+Key)mod26
public String getEncryptText(String alpha, int key, String message)
{
StringBuilder encryptText = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
if(message.charAt(i) == ' ') {
encryptText.append(' ');
} else {
pVal = alpha.indexOf(message.charAt(i));
//encrypt formula
encryptFormula = (pVal+key)%26;
encryptChar = alpha.charAt(encryptFormula);
encryptText.append(encryptChar);
}
}
return encryptText.toString();
}
}
class Decrypt
{
// PlainText = (CipherText-Key)mod26
int cVal, decryptFormula;
char decryptChar;
public String getDecryptText(String alpha, int key, String message)
{
StringBuilder decryptText = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
if(message.charAt(i) == ' ') {
decryptText.append(' ');
} else {
cVal = alpha.indexOf(message.charAt(i));
//decrypt formula
decryptFormula = (cVal-key)%26;
decryptChar = alpha.charAt(decryptFormula);
decryptText.append(decryptChar);
}
}
return decryptText.toString();
}
}
public class CaesarCipher {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("Enter the value of Key: (in int only)");
int valOfKey=in.nextInt();
in.nextLine();
System.out.println("Enter the message: ");
String message = in.nextLine();
String convertToUpperCase = message.toUpperCase();
Encrypt encrypt = new Encrypt();
String cipherText = encrypt.getEncryptText(alphabets, valOfKey, convertToUpperCase);
System.out.println("Encryption Message: " +cipherText);
Decrypt decrypt = new Decrypt();
String plainText = decrypt.getDecryptText(alphabets, valOfKey, cipherText);
System.out.println("Decryption Message: " +plainText);
}
}