forked from Ayushsinhahaha/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAffine Cypher
93 lines (85 loc) · 2.17 KB
/
Affine Cypher
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
/// Encryption
E ( x ) = ( a x + b ) mod m
modulus m: size of the alphabet
a and b: key of the cipher.
/// Decryption
D ( x ) = a^-1 ( x - b ) mod m
a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation
1 = a^-1 mod m.
/// Algorithms
Begin
Function encryption(string m)
for i = 0 to m.length()-1
if(m[i]!=' ')
c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A')
else
c += m[i]
return c
End
Begin
Function decryption(string c)
Initialize a_inverse = 0
Initialize flag = 0
For i = 0 to 25
flag = (a * i) % 26
if (flag == 1)
a_inverse = i
done
done
For i = 0 to c.length() - 1
if(c[i]!=' ')
m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A')
else
m = m+ c[i]
done
End
/// CODE ////
#include<bits/stdc++.h>
using namespace std;
static int a = 7;
static int b = 6;
string encryption(string m) {
//Cipher Text initially empty
string c = "";
for (int i = 0; i < m.length(); i++) {
// Avoid space to be encrypted
if(m[i]!=' ')
// added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A');
else
//else append space character
c += m[i];
}
return c;
}
string decryption(string c) {
string m = "";
int a_inverse = 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_inverse = i;
}
}
for (int i = 0; i < c.length(); i++) {
if(c[i] != ' ')
// added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A');
else
//else append space character
m += c[i];
}
return m;
}
int main(void) {
string msg = "TUTORIALSPOINT";
string c = encryption(msg);
cout << "Encrypted Message is : " << c<<endl;
cout << "Decrypted Message is: " << decryption(c);
return 0;
}