md5_encryption.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import StringIO
  2. import hashlib
  3. def md5_encrypt(data, key):
  4. if len(data) % 16 != 0:
  5. data += (16 - (len(data) % 16)) * '\x00'
  6. hash_block = []
  7. output = ''
  8. last_hash = ''
  9. for c in data:
  10. md5_ctx = hashlib.md5()
  11. md5_ctx.update(c)
  12. md5_ctx.update(key)
  13. md5_ctx.update(last_hash)
  14. hash_block.append(md5_ctx.digest())
  15. last_hash = hash_block[-1]
  16. if len(hash_block) == 16:
  17. cur_block = ''
  18. for b in hash_block:
  19. cur_block += b
  20. md5_ctx = hashlib.md5()
  21. md5_ctx.update(cur_block)
  22. last_hash = md5_ctx.digest()
  23. output += cur_block + last_hash
  24. hash_block = []
  25. return output
  26. def md5_decrypt(data, key):
  27. reader = StringIO.StringIO(data)
  28. output = ''
  29. last_hash = ''
  30. while 1:
  31. cur_block = ''
  32. for i in range(16):
  33. cur_hash = reader.read(16)
  34. if len(cur_hash) != 16:
  35. return output
  36. cur_block += cur_hash
  37. cur_byte = '\x00'
  38. for i in range(0x100):
  39. md5_ctx = hashlib.md5()
  40. cur_byte = chr(i)
  41. md5_ctx.update(cur_byte)
  42. md5_ctx.update(key)
  43. md5_ctx.update(last_hash)
  44. if cur_hash == md5_ctx.digest():
  45. break
  46. output += cur_byte
  47. last_hash = cur_hash
  48. md5_ctx = hashlib.md5()
  49. md5_ctx.update(cur_block)
  50. last_hash = reader.read(16)
  51. if last_hash != md5_ctx.digest():
  52. raise Exception("Hash mismatch! Incorrect key or corrupt data")