forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaffine.cpp
More file actions
138 lines (67 loc) · 2.02 KB
/
affine.cpp
File metadata and controls
138 lines (67 loc) · 2.02 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//CPP program to illustrate Affine Cipher
#include<bits/stdc++.h>
using namespace std;
//Key values of a and b
const int a = 11;
const int b = 20;
string encryptMessage(string msg)
{
///Cipher Text initially empty
string cipher = "";
for (int i = 0; i < msg.length(); i++)
{
// Avoid space to be encrypted
if(msg[i]!=' ')
/* applying encryption formula ( a x + b ) mod m
{here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
cipher = cipher +
(char) ((((a * (msg[i]-'A') ) + b) % 26) + 'A');
else
//else simply append space character
cipher += msg[i];
}
return cipher;
}
string decryptCipher(string cipher)
{
string msg = "";
int a_inv = 0;
int flag = 0;
//Find a^-1 (the multiplicative inverse of a
//in the group of integers modulo m.)
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
//Check if (a*i)%26 == 1,
//then i will be the multiplicative inverse of a
if (flag == 1)
{
a_inv = i;
}
}
for (int i = 0; i < cipher.length(); i++)
{
if(cipher[i]!=' ')
/*Applying decryption formula a^-1 ( x - b ) mod m
{here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
msg = msg +
(char) (((a_inv * ((cipher[i]+'A' - b)) % 26)) + 'A');
else
//else simply append space character
msg += cipher[i];
}
return msg;
}
//Driver Program
int main(void)
{
string msg = "Computer";
//Calling encryption function
string cipherText = encryptMessage(msg);
cout << "Encrypted Message is : " << cipherText<<endl;
//Calling Decryption function
cout << "Decrypted Message is: " << decryptCipher(cipherText);
return 0;
}