forked from mrizky-kur/Redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaesarCipherExample.java
88 lines (69 loc) · 3.41 KB
/
CaesarCipherExample.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
88
// import required classes and package, if any
import java.util.Scanner;
// create class CaesarCipherExample for encryption and decryption
public class CaesarCipherExample
{
// ALPHABET string denotes alphabet from a-z
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
// create encryptData() method for encrypting user input string with given shift key
public static String encryptData(String inputStr, int shiftKey)
{
// convert inputStr into lower case
inputStr = inputStr.toLowerCase();
// encryptStr to store encrypted data
String encryptStr = "";
// use for loop for traversing each character of the input string
for (int i = 0; i < inputStr.length(); i++)
{
// get position of each character of inputStr in ALPHABET
int pos = ALPHABET.indexOf(inputStr.charAt(i));
// get encrypted char for each char of inputStr
int encryptPos = (shiftKey + pos) % 26;
char encryptChar = ALPHABET.charAt(encryptPos);
// add encrypted char to encrypted string
encryptStr += encryptChar;
}
// return encrypted string
return encryptStr;
}
// create decryptData() method for decrypting user input string with given shift key
public static String decryptData(String inputStr, int shiftKey)
{
// convert inputStr into lower case
inputStr = inputStr.toLowerCase();
// decryptStr to store decrypted data
String decryptStr = "";
// use for loop for traversing each character of the input string
for (int i = 0; i < inputStr.length(); i++)
{
// get position of each character of inputStr in ALPHABET
int pos = ALPHABET.indexOf(inputStr.charAt(i));
// get decrypted char for each char of inputStr
int decryptPos = (pos - shiftKey) % 26;
// if decryptPos is negative
if (decryptPos < 0){
decryptPos = ALPHABET.length() + decryptPos;
}
char decryptChar = ALPHABET.charAt(decryptPos);
// add decrypted char to decrypted string
decryptStr += decryptChar;
}
// return decrypted string
return decryptStr;
}
// main() method start
public static void main(String[] args)
{
// create an instance of Scanner class
Scanner sc = new Scanner(System.in);
// take input from the user
System.out.println("Enter a string for encryption using Caesar Cipher: ");
String inputStr = sc.nextLine();
System.out.println("Enter the value by which each character in the plaintext message gets shifted: ");
int shiftKey = Integer.valueOf(sc.nextLine());
System.out.println("Encrypted Data ===> "+encryptData(inputStr, shiftKey));
System.out.println("Decrypted Data ===> "+decryptData(encryptData(inputStr, shiftKey), shiftKey));
// close Scanner class object
sc.close();
}
}