Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. from collections import Counter
  2. import sys
  3. import string
  4. import base64
  5. from Crypto.Hash import SHA256
  6. from random import randint
  7. def raw2hex(raw):
  8. return raw.encode('hex')
  9.  
  10.  
  11. def hex2raw(hexstring):
  12. return base64.b16decode(hexstring)
  13.  
  14. hexdigits = '0123456789ABCDEF'
  15.  
  16. def hash(message):
  17. h = SHA256.new()
  18. h.update(message)
  19. return h.digest()
  20.  
  21.  
  22. def main():
  23. # Try to find a collision on the first 4 bytes (32 bits)
  24.  
  25. # Step 1. Generate 2^16 different random messages
  26. while True:
  27. messages = []
  28. for i in range(1 << 16):
  29. msg = ""
  30. for j in range(8):
  31. msg = msg + chr(randint(0, 255))
  32. messages.append(msg)
  33.  
  34. # Step 2. Compute hashes
  35. hashes = []
  36. fullhashes = []
  37. for msg in messages:
  38. hashes.append(hash(msg)[:4])
  39. fullhashes.append(hash(msg))
  40.  
  41.  
  42. # Step 3. Check if there exist two hashes that match in the first
  43. # four bytes.
  44. l = [k for k,v in Counter(hashes).items() if v>1]
  45.  
  46. if len(l) == 0:
  47. continue
  48.  
  49. # Step 3a. If a match is found, print the messages and hashes
  50. indices = [i for i, x in enumerate(hashes) if x == l[0]]
  51. for i in indices:
  52. print "Hash ", raw2hex(fullhashes[i])
  53. print "Message ", raw2hex(messages[i])
  54.  
  55. # Step 3b. If no match is found, repeat the attack with a new set
  56. # of random messages
  57.  
  58. if __name__ == "__main__":
  59. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement