Advertisement
CSenshi

Cryptography - HW3.2 (sign.py)

Jan 10th, 2020
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. from oracle import *
  2. from helper import *
  3.  
  4. # xgcd(a,b) and modinv(a,b) taken from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
  5.  
  6.  
  7. def xgcd(a, b):
  8.     """return (g, x, y) such that a*x + b*y = g = gcd(a, b)"""
  9.     x0, x1, y0, y1 = 0, 1, 1, 0
  10.     while a != 0:
  11.         (q, a), b = divmod(b, a), a
  12.         y0, y1 = y1, y0 - q * y1
  13.         x0, x1 = x1, x0 - q * x1
  14.     return b, x0, y0
  15.  
  16.  
  17. def modinv(a, b):
  18.     """return x such that (x * a) % b == 1"""
  19.     g, x, _ = xgcd(a, b)
  20.     if g != 1:
  21.         raise Exception('gcd(a, b) != 1')
  22.     return x % b
  23.  
  24.  
  25. def sign(challenge, N):
  26.     ''' Step 0 : Initialize Conecction '''
  27.     Oracle_Connect()
  28.  
  29.     ''' Step 1 : convert original message to integers'''
  30.     m = ascii_to_int(challenge)
  31.  
  32.     ''' Step 2 : HACKING!!! '''
  33.     # divide msg into two parts
  34.     m1 = 7
  35.     m2 = m / m1
  36.     # inverse of sign(1) over N
  37.     inverse_1 = modinv(Sign(1), N)
  38.     # evaluate new sign
  39.     r = (Sign(m1) * Sign(m2) * inverse_1) % N
  40.  
  41.     ''' Step 3 : Check if sign is correcy'''
  42.     if Verify(m, r):
  43.         print 'Sign Verified!'
  44.         print r
  45.     else:
  46.         print 'Sign Verification Failed'
  47.  
  48.     ''' Step 4: Disconect from server '''
  49.     Oracle_Disconnect()
  50.  
  51.  
  52. def main():
  53.     challenge = 'Crypto is hard --- even schemes that look complex can be broken'
  54.     N = 119077393994976313358209514872004186781083638474007212865571534799455802984783764695504518716476645854434703350542987348935664430222174597252144205891641172082602942313168180100366024600206994820541840725743590501646516068078269875871068596540116450747659687492528762004294694507524718065820838211568885027869
  55.     sign(challenge, N)
  56.  
  57.  
  58. if __name__ == '__main__':
  59.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement