Advertisement
CSenshi

Cryptography - HW2.2 (forge.py)

Jan 9th, 2020
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. import itertools
  2. import oracle as O
  3. import time
  4. import sys
  5.  
  6. CHUNK_LENGTH = 16
  7.  
  8.  
  9. def split_into_chunks(arr, n):
  10.     chunk_arr = []
  11.     for i in range(0, len(arr), n):
  12.         # get current chunk
  13.         chunk = arr[i:i + n]
  14.         # append to list
  15.         chunk_arr += [chunk]
  16.     return chunk_arr
  17.  
  18.  
  19. def verify(message, tag):
  20.     ret = O.Vrfy(message, len(message), tag)
  21.     if ret == 1:
  22.         print "Tag verified!"
  23.     else:
  24.         print "Tag Rejected!"
  25.  
  26.  
  27. def break_CBC_MAC(message):
  28.     ''' Step 0 : Connect to server '''
  29.     O.Oracle_Connect()
  30.  
  31.     ''' Step 1 : Convert characters to integers'''
  32.     message = list(map(ord, message))
  33.  
  34.     ''' Step 2 : Divide into chunks'''
  35.     chunks = split_into_chunks(message, CHUNK_LENGTH)
  36.  
  37.     '''' Step 3 : For each pair evaluate new Mac '''
  38.     # starting mac filled with zeros
  39.     tag = bytearray([0]*CHUNK_LENGTH*2)
  40.     for i in range(0, len(chunks), 2):
  41.         # get pairs of chunks
  42.         curr_chunk = chunks[i]
  43.         next_chunk = chunks[i + 1]
  44.  
  45.         # create new msg with xoring to old tag
  46.         xord_chunk = [curr_chunk[i] ^ tag[i] for i in range(CHUNK_LENGTH)]
  47.  
  48.         # evaluate new tag
  49.         tag = O.Mac(xord_chunk + next_chunk, 2 * CHUNK_LENGTH)
  50.  
  51.     ''' Step 5: Verify Our Tag'''
  52.     verify(message, tag)
  53.  
  54.     ''' Step 6: Disconnect from server '''
  55.     O.Oracle_Disconnect()
  56.  
  57.     return tag
  58.  
  59.  
  60. if __name__ == "__main__":
  61.     if len(sys.argv) != 2:
  62.         print('Should pass exactly 1 argument: python forge.py <message>')
  63.         exit()
  64.  
  65.     '''Input '''
  66.     # filename
  67.     message_filename = sys.argv[1]
  68.     # open and read file
  69.     with open(message_filename, 'r') as message_file:
  70.         message = message_file.read()
  71.  
  72.     ''' Break Code '''
  73.     plain_text = break_CBC_MAC(message)
  74.  
  75.     ''' Output '''
  76.     print(plain_text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement