-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathHillCipher.cpp
108 lines (83 loc) · 2.63 KB
/
HillCipher.cpp
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
/* This code is an implementation of Hill Cipher. It
is a polygraphic substitution cipher. It forms a
nxn matrix of key and nx1 matrix(s) of the plaintext
and then multiplies the two matrices to obtains the
matrix of ciphertext.*/
#include<bits/stdc++.h>
using namespace std;
#define SIZE 3
//This function prints the cipher text
void printciphertext(int cipherMatrix[SIZE][1]){
string output;
for(int i=0;i<SIZE;i++){
output += cipherMatrix[i][0]+97;
}
cout<<"The cipher text is :"<<output;
}
//This function calculates the matrix multiplication
void cipher(int cipherMatrix[SIZE][1],int keyMatrix[SIZE][SIZE],int plaintextMatrix[SIZE][1]){
//calculating the multiplication
for(int i=0;i<SIZE;i++){
cipherMatrix[i][0] = 0;
for(int j=0;j<SIZE;j++){
cipherMatrix[i][0] += keyMatrix[i][j]*plaintextMatrix[j][0];
}
cipherMatrix[i][0] = cipherMatrix[i][0]%26;
}
}
//This function builds the key matrix
void buildkeyMatrix(int keyMatrix[SIZE][SIZE],string key){
int counter =0;
//storing the key in matrix
for(int i=0;i<SIZE;i++){
for(int j=0;j<SIZE;j++){
keyMatrix[i][j] = key[counter]%97;
counter++;
}
}
}
//This function builds the plaintext matrix
void buildplaintextMatrix(int plaintextMatrix[][1],string plaintext){
//storing the plaintext in matrix form
for(int i=0;i<SIZE;i++){
plaintextMatrix[i][0] = (plaintext[i])%97;
}
}
//This fuinction helps us in calling all the functions in sequential order
void hillcipher(string plaintext,string key){
int plaintextMatrix[SIZE][1];
buildplaintextMatrix(plaintextMatrix,plaintext);
int keyMatrix[SIZE][SIZE];
buildkeyMatrix(keyMatrix,key);
int cipherMatrix[SIZE][1];
cipher(cipherMatrix,keyMatrix,plaintextMatrix);
printciphertext(cipherMatrix);
}
int main(){
string plaintext;
string key;
cout<<"The plaintext size you need to enter is :"<<SIZE<<endl;
cout<<"Enter the plaintext here same :";
//Taking plaintext from here
cin>>plaintext;
cout<<"Enter the key here :";
//Taking key from here
cin>>key;
int size1 = plaintext.length();
int size2 = key.length();
//validating for the input given
if(size2 != size1*size1 || size1 != SIZE){
cout<<"The key input is wrong!"<<endl;
return 0;
}
else
hillcipher(plaintext,key);
return 0;
}
/*
Sample I/O :
The plaintext size you need to enter is :3
Enter the plaintext here same :ask
Enter the key here :thisiskey
The cipher text is :yma
*/