Subversion Repositories Code-Repo

Compare Revisions

Ignore whitespace Rev 218 → Rev 219

/Classwork/MATH4176 - Cryptography 2/ElGamal.py
0,0 → 1,82
# Encrypted Data
data_set = ((3781,14409),(31552,3930),(27214,15442),(5809,30274),
(5400,31486),(19936,721),(27765,29284),(29820,7710),
(31590,26470),(3781,14409),(15898,30844),(19048,12914),
(16160,3129),(301,17252),(24689,7776),(28856,15720),
(30555,24611),(20501,2922),(13659,5015),(5740,31233),
(1616,14170),(4294,2307),(2320,29174),(3036,20132),
(14130,22010),(25910,19663),(19557,10145),(18899,27609),
(26004,25056),(5400,31486),(9526,3019),(12962,15189),
(29538,5408),(3149,7400),(9396,3058),(27149,20535),
(1777,8737),(26117,14251),(7129,18195),(25302,10248),
(23258,3468),(26052,20545),(21958,5713),(346,31194),
(8836,25898),(8794,17358),(1777,8737),(25038,12483),
(10422,5552),(1777,8737),(3780,16360),(11685,133),
(25115,10840),(14130,22010),(16081,16414),(28580,20845),
(23418,22058),(24139,9580),(173,17075),(2016,18131),
(19886,22344),(21600,25505),(27119,19921),(23312,16906),
(21563,7891),(28250,21321),(28327,19237),(15313,28649),
(24271,8480),(26592,25457),(9660,7939),(10267,20623),
(30499,14423),(5839,24179),(12846,6598),(9284,27858),
(24875,17641),(1777,8737),(18825,19671),(31306,11929),
(3576,4630),(26664,27572),(27011,29164),(22763,8992),
(3149,7400),(8951,29435),(2059,3977),(16258,30341),
(21541,19004),(5865,29526),(10536,6941),(1777,8737),
(17561,11884),(2209,6107),(10422,5552),(19371,21005),
(26521,5803),(14884,14280),(4328,8635),(28250,21321),
(28327,19237),(15313,28649))
 
def Extended_Euclidian(a, b):
''' Takes values a and b and returns a tuple (r,s,t) in the following format:
r = s * a + t * b where r is the GCD and s and t are the inverses of a and b'''
t_ = 0
t = 1
s_ = 1
s = 0
q = a//b
r = a - q * b
# print("%d\t= %d * %d + %d" % (a, q, b, r))
while r > 0:
temp = t_ - q * t
t_ = t
t = temp
temp = s_ - q * s
s_ = s
s = temp
a = b
b = r
q = a//b
r = a - q * b
# print("%d\t= %d * %d + %d" % (a, q, b, r))
r = b
return (r, s, t)
 
def Inverse(a, b):
'''Returns the multiplicative inverse of a mod b'''
ret = Extended_Euclidian(a,b)
if (ret[1] < 0):
inv = ret[1] + b
else:
inv = ret[1]
return inv
 
def Decrypt(n):
'''Decodes an encoding where n = a * 26^2 + b * 26 + c'''
a = int(n / 676)
n = n - (a * 676)
b = int(n / 26)
n = n - (b * 26)
c = n
return (a, b, c)
 
if __name__ == '__main__':
p = 31847
a = 7899
 
# For each encrypted data packet, decrypt it using the following function:
# d(y_1,y_2) = y_2(y_1^a)^-1 mod p
for i in data_set:
d = i[1] * Inverse(i[0]**a,p) % p
s = Decrypt(d)
print("%c%c%c" % (chr(s[0]+65), chr(s[1]+65), chr(s[2]+65)), end='')
print()