Skip to content

Commit 0c80fff

Browse files
Demo
1 parent 2c15b8c commit 0c80fff

1 file changed

Lines changed: 90 additions & 0 deletions

File tree

ciphers/lab2.cpp

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include<iostream>
2+
#include<vector>
3+
#include<string>
4+
5+
using namespace std;
6+
7+
int modInverse(int n)
8+
{
9+
n %= 26;
10+
for(int i = 0; i < 26; i++)
11+
{
12+
if((n * i) % 26 == 1)
13+
return i;
14+
}
15+
return -1;
16+
}
17+
18+
string encrypt(string text, int key[2][2])
19+
{
20+
string cipher = "";
21+
for(int i = 0; i < text.length(); i += 2)
22+
{
23+
int p1 = text[i] - 'A';
24+
int p2 = text[i+1] - 'A';
25+
26+
cipher += char((key[0][0]*p1 + key[0][1]*p2) % 26 + 'A');
27+
cipher += char((key[1][0]*p1 + key[1][1]*p2) % 26 + 'A');
28+
}
29+
return cipher;
30+
}
31+
32+
string decrypt(string cipher, int key[2][2])
33+
{
34+
int det = (key[0][0]*key[1][1] - key[0][1]*key[1][0]) % 26;
35+
if(det < 0) det += 26;
36+
37+
int invdet = modInverse(det);
38+
if(invdet == -1) return "Key is not invertible";
39+
40+
int invKey[2][2];
41+
42+
invKey[0][0] = ( key[1][1] * invdet ) % 26;
43+
invKey[0][1] = (-key[0][1] * invdet ) % 26;
44+
invKey[1][0] = (-key[1][0] * invdet ) % 26;
45+
invKey[1][1] = ( key[0][0] * invdet ) % 26;
46+
47+
for(int i = 0; i < 2; i++)
48+
for(int j = 0; j < 2; j++)
49+
if(invKey[i][j] < 0)
50+
invKey[i][j] += 26;
51+
52+
string plain = "";
53+
54+
for(int i = 0; i < cipher.length(); i += 2)
55+
{
56+
int c1 = cipher[i] - 'A';
57+
int c2 = cipher[i+1] - 'A';
58+
59+
plain += char((invKey[0][0]*c1 + invKey[0][1]*c2) % 26 + 'A');
60+
plain += char((invKey[1][0]*c1 + invKey[1][1]*c2) % 26 + 'A');
61+
}
62+
63+
return plain;
64+
}
65+
66+
int main()
67+
{
68+
int key[2][2];
69+
string message;
70+
71+
cout << "Enter 4 integers for the key matrix (2x2): ";
72+
for(int i = 0; i < 2; i++)
73+
for(int j = 0; j < 2; j++)
74+
cin >> key[i][j];
75+
76+
cout << "Enter message (uppercase letters only): ";
77+
cin >> message;
78+
79+
// Ensure even length
80+
if(message.length() % 2 != 0)
81+
message += 'X';
82+
83+
string cipher = encrypt(message, key);
84+
cout << "Encrypted message: " << cipher << endl;
85+
86+
string decrypted = decrypt(cipher, key);
87+
cout << "Decrypted message: " << decrypted << endl;
88+
89+
return 0;
90+
}

0 commit comments

Comments
 (0)