Python Help! Decrypt Function using a Multiplicative inverse function. Here is t
ID: 3841793 • Letter: P
Question
Python Help! Decrypt Function using a Multiplicative inverse function.
Here is the code that I have so far, I have a multiplicative inverse function that use an Extended Euclidean Algorithm function. I need to use these the multinv function to create a decrypt function. "Write a function called decrypt that accepts three numbers (c, m, and k) and returns the corresponding plaintext (p) value as a number. You can assume the modulus (n) is 256. You will need to compute the multiplicative inverse of m mod 256 to decipher c."
# Problem 1: Extended Euclidean Algorithm
def egcd(a, b):
  if b == 0:
     return (1, 0)
  else:
     # Calculate q
     q = a // b
     # Calculate r
     r = a % b
     # Calculate (s, t) by calling egcd(b, r)
     (s,t) = egcd(b, r)
     return (t, s-q*t)
# Problem 2: Multiplicative Inverse
def multinv(a, n):
g = egcd(a, n)
return g[0] % n
# Problem 3: Decrypt a Single Value
def decrypt(c, m, k):
for testing purpose, running decrypt(80, 5, 11) should return 65
Explanation / Answer
def gcd(x, y):
while(y):
x, y = y , x % y
return x
def lcm(a, b):
 Â
return abs(a*b) / gcd(a,b)
def egcd(a, b):
 Â
if b == 0:
return (1, 0)
else:
q = a // b
r = a % b
(s, t) = egcd(b, r)
return (t, s - q * t)
def multinv(m, n):
 Â
(x, y) = egcd(m, n)
return x % n
 Â
def decrypt(m, e, k):
return (e-k) * multinv(m, 256) % 256
def linearcipher(bstr, m, k):
return bytes( [ (m*b+k) % 256 for b in bstr] )
def lineardecipher(lstr, m, k):
 Â
return bytes ( (decrypt (m, e, k) ) for e in lstr)
import unittest
class MyTest(unittest.TestCase):
def test_gcd(self):
self.assertEqual( gcd(42, 35) , 7 )
self.assertEqual( gcd(37, 16) , 1 )
self.assertEqual( gcd(52, 81), 1 )
self.assertEqual( gcd(10, 15), 5 )
self.assertEqual( gcd(5,5), 5)
def test_lcm(self):
self.assertEqual( lcm(3,1) , 3 )
self.assertEqual( lcm(5,0) , 0 )
self.assertEqual( lcm(11, 3), 33 )
def test_egcd(self):
self.assertEqual( egcd(6, 4) , (1, -1) )
self.assertEqual( egcd(6, 3) , (0, 1) )
self.assertEqual( egcd(9,6), (1,-1) )
def test_multinv(self):
self.assertEqual( multinv(15, 26) , 7 )
self.assertEqual( multinv(7,26), 15 )
def test_linearcipher(self):
self.assertEqual(linearcipher(b'Hello Sierra', 5, 11), b"s''6«ªEEð")
self.assertEqual(linearcipher(b'Discrete Structures', 11, 83), b'?ÖD”9ªOª³äO9Z”OZ9ªD')
self.assertEqual(linearcipher(b'Sierra', 11, 83), b'äÖª99~')
def test_lineardecipher(self):
self.assertEqual(lineardecipher(b"s''6«ªEEð", 5, 11), b'Hello Sierra')
 Â
def test_decrypt(self):
self.assertEqual( decrypt(5, 61, 11), 10)
self.assertEqual( decrypt(5, 80, 11), 65)
self.assertEqual( decrypt(5, 149, 11), 130)
unittest.main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.