-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAffine-Cipher.py
More file actions
executable file
·39 lines (23 loc) · 860 Bytes
/
Affine-Cipher.py
File metadata and controls
executable file
·39 lines (23 loc) · 860 Bytes
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
# Affine Cipher using co-prime
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
VALUES = dict(zip(LETTERS, range(len(LETTERS))))
RVALUES = dict(zip(range(len(LETTERS)), LETTERS))
def find_coprime(a):
for i in range(26):
if ((i * a) % 26) == 1:
return i
# Raise an error
raise Exception, "The codeword %d has not a coprime, try another" % a
def encode_affine(msg, a, b):
encoded_message = [RVALUES[(a * VALUES[i] + b) % 26] for i in msg]
return ''.join(encoded_message)
def decode_affine(msg, a, b):
decode_affine('FPAMPIQQWVMFPITWU', 5, 8)
# Inverse of the modulo
m = find_coprime(a)
decoded_message = [RVALUES[(m * (VALUES[i] - b)) % 26] for i in msg]
return ''.join(decoded_message)
ptxt='PROGRAMMINGPRAXIS'
print encode_affine(ptxt,5,8)
ctxt='FPAMPIQQWVMFPITWU'
print decode_affine(ctxt,5,8)