-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaffine.py
36 lines (34 loc) · 971 Bytes
/
affine.py
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
import sys
sys.path.append("../..")
from MyCrypto.algorithms.exgcd import gcd, inverse
def affine(x, key, mod=26, method='encrypt'):
a, b = key
if gcd(a, mod) != 1:
return -1
if method == 'encrypt':
if not x.islower():
return -1
forward = dict()
for i in range(26):
forward[chr(ord('a')+i)] = chr(ord('A')+(a*i+b)%mod)
code = str()
for c in x:
code += forward[c]
return code
elif method == 'decrypt':
if not x.isupper():
return -1
backward = dict()
for i in range(26):
backward[chr(ord('A')+i)] = chr(ord('a')+(i-b+mod)*inverse(a, mod)%mod)
code = str()
for c in x:
code += backward[c]
return code
else:
return -1
if __name__ == '__main__':
key = (25, 3)
s = 'cryptography'
print(affine(s, key))
print(affine('BMFOKPXMDOWF', key, method='decrypt'))