-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVigenèreCipher.java
108 lines (84 loc) · 2.91 KB
/
VigenèreCipher.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import static java.lang.System.out;
import java.util.Scanner;
/**
*
* @author Omniyyah
*/
public class VigenèreCipher {
public static Scanner in = new Scanner(System.in);
public static char[][] table = new char[26][26];
public static void makeTable() {
char ch = 'A';
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
int x = ((((int) ch - 65) + j) % 26) + 65;
table[i][j] = (char) x;
}
ch++;
}
}
public static void printTable() {
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
out.print(table[i][j] + " ");
}
}
}
public static char getCharFromTable(int row, int col) {
return table[row][col];
}
public static String encryption(String msg, String key) {
String cipherText = "";
msg = msg.toUpperCase().replaceAll(" ", "");
key = key.toUpperCase().replaceAll(" ", "");
int keyLength = key.length();
for (int i = 0; i < msg.length(); i++) {
int x = ((int) (msg.charAt(i)) - 65);
int y = (((int) (key.charAt((i % keyLength)))) - 65);
cipherText += getCharFromTable(x, y);
}
return cipherText;
}
public static String decryption(String msg, String key) {
String plainText = "";
msg = msg.toUpperCase().replaceAll(" ", "");
key = key.toUpperCase().replaceAll(" ", "");
int keyLength = key.length();
for (int i = 0; i < msg.length(); i++)
{
int x = (((int) msg.charAt(i)) - 65);
int y = (((int) (key.charAt((i % keyLength)))) - 65);
char ch = msg.charAt(i);
int j;
for (j = 0; j < 26; j++) {
if (getCharFromTable(y, j) == ch) {
break;
}
}
plainText += getCharFromTable(0, j);
}
return plainText;
}
public static void main(String[] args) {
makeTable();
out.println("if you want encryption press 1,if you want decryption press 2");
int command = in.nextInt();
in.nextLine();
switch (command) {
case 1:
out.println("Please enter your message");
String msgToEencrypt = in.nextLine();
out.println("Please enter your key");
String keyToEencrypt = in.nextLine();
out.println(encryption(msgToEencrypt, keyToEencrypt));
break;
case 2:
out.println("Please enter your message");
String msgToDecrypt = in.nextLine();
out.println("Please enter your key");
String keyToDecrypt = in.nextLine();
out.println(decryption(msgToDecrypt, keyToDecrypt));
break;
}
}
}