generated from CodeChefVIT/template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mask.py
69 lines (61 loc) · 1.48 KB
/
mask.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
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
from decouple import config
p=config('p', cast=int)
q=config('q', cast=int)
r=config('r', cast=int)
n=p*q*r
phi=(p-1)*(q-1)*(r-1)
def gcd(a, b):
while b != 0:
c = a % b
a = b
b = c
return a
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
#raise Exception('modular inverse does not exist')
return -1
else:
return x % m
def coprimes(a):
l = []
for x in range(2, a):
if gcd(a, x) == 1 and modinv(x,phi) != None:
l.append(x)
for x in l:
if x == modinv(x,phi):
l.remove(x)
return l
l=coprimes(phi)
e=l[int(len(l)/2)]
d=modinv(e,phi)
def encrypt_block(m):
c = modinv(m**e, n)
if c == -1:
return ord('o')
return c
def decrypt_block(c):
m = modinv(c**d, n)
if m == -1:
return ord('o')
return m
def encrypt_string(s):
return ''.join([chr(encrypt_block(ord(x))) for x in list(s)])
def decrypt_string(s):
return ''.join([chr(decrypt_block(ord(x))) for x in list(s)])
if __name__=="__main__":
print("public key = ",e,n)
print("private key= ",d,n)
s = input("Enter a message to encrypt: ")
print("\nPlain message: " + s + "\n")
enc = encrypt_string(s)
print("Encrypted message: " + enc + "\n")
print(type(enc))
dec = decrypt_string(enc)
print("Decrypted message: " + dec + "\n")