-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHillCipher.java
43 lines (36 loc) · 1.32 KB
/
HillCipher.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
import java.util.Scanner;
public class HillCipher{
private static Scanner sc = new Scanner(System.in);
private static void encryption(String msg){
//for making msg length even
if(msg.length() % 2 != 0){
msg += "z";
}
int msgNum[] = new int [msg.length()];
for(int i = 0;i < msg.length(); i++){
msgNum[i] = ((int)msg.charAt(i)) - 65;
//System.out.println(msgNum[i]);
}
int key[][] = new int [2][2];
System.out.println("Enter the key(2*2 matrix having inverse):");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
key[i][j] = sc.nextInt();
}
}
String eText = "";
for(int i = 0; i < msg.length(); i += 2){
int temp1 = msgNum[i] * key[0][0] + msgNum[i+1] * key[1][0];
eText += (char) ((temp1 % 26) + 65);
int temp2 = msgNum[i] * key[0][1] + msgNum[i+1] * key[1][1];
eText += (char) ((temp2 % 26) + 65);
}
System.out.println("Encrypted Text:" + eText);
}
public static void main(String[] args){
System.out.print("Enter message(word only): ");
String msg = sc.next();
msg = msg.toUpperCase();
encryption(msg);
}
}