forked from AllAlgorithms/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCeasercipher.java
More file actions
63 lines (57 loc) · 1.85 KB
/
Ceasercipher.java
File metadata and controls
63 lines (57 loc) · 1.85 KB
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
import java.util.Scanner;
/**
* The All Algorithms Project
*
* @contributor @chikaslocalhost
*/
public class Ceasercipher {
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
/**
* Encryption using plaintext and shiftkey
*
* @param plainText
* @param shiftKey
* @return
*/
public static String encrypt(String plainText, int shiftKey) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++) {
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
/**
* Decryption using encrypted value and shift key which used in encryption.
*
* @param cipherText
* @param shiftKey
* @return
*/
public static String decrypt(String cipherText, int shiftKey) {
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++) {
int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
System.out.println(encrypt(message, 3));
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}