-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaesarCipher.java
87 lines (72 loc) · 2.17 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
83
84
85
86
87
import java.util.Scanner;
public class CaesarCipher
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static void encryption(String msg,int shift)
{
msg=msg.toLowerCase();
String cipher= "";
for(int i=0;i<msg.length();i++)
{
if(msg.charAt(i) == ' ')
{
cipher+=" ";
}
else
{
int charPosition = ALPHABET.indexOf(msg.charAt(i));
int keyVal = (shift + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipher += replaceVal;
}
}
System.out.println(cipher);
}
public static void decryption(String msg,int shift)
{
msg = msg.toLowerCase();
String plainText = "";
for (int i = 0; i < msg.length(); i++)
{
if(msg.charAt(i) == ' ')
{
plainText+=" ";
}
else
{
int charPosition = ALPHABET.indexOf(msg.charAt(i));
int keyVal = (charPosition - shift) % 26;
if (keyVal < 0)
{
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
}
System.out.println(plainText);
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("if you want encryption press 1,if you want decryption press 2");
int n=in.nextInt();
in.nextLine();
if(n==1)
{
System.out.println("Please enter your message");
String msg=in.nextLine();
System.out.println("Please enter your key");
int k=in.nextInt();
encryption(msg,k);
}
if(n==2)
{
System.out.println("Please enter your message");
String msg=in.nextLine();
System.out.println("Please enter your key");
int k=in.nextInt();
decryption(msg,k);
}
}
}