DH.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. class DH_Endpoint(object):
  2. def __init__(self, public_key1, public_key2, private_key):
  3. self.public_key1 = public_key1
  4. self.public_key2 = public_key2
  5. self.private_key = private_key
  6. self.full_key = None
  7. def generate_partial_key(self):
  8. partial_key = self.public_key1**self.private_key
  9. partial_key = partial_key%self.public_key2
  10. return partial_key
  11. def generate_full_key(self, partial_key_r):
  12. full_key = partial_key_r**self.private_key
  13. full_key = full_key%self.public_key2
  14. self.full_key = full_key
  15. return full_key
  16. def encrypt_message(self, message):
  17. encrypted_message = ""
  18. key = self.full_key
  19. for c in message:
  20. encrypted_message += chr(ord(c)+key)
  21. return encrypted_message
  22. def decrypt_message(self, encrypted_message):
  23. decrypted_message = ""
  24. key = self.full_key
  25. for c in encrypted_message:
  26. decrypted_message += chr(ord(c)-key)
  27. return decrypted_message
  28. def generate_partial_key(self):
  29. partial_key = self.public_key1**self.private_key
  30. partial_key = partial_key%self.public_key2
  31. return partial_key
  32. def generate_full_key(self, partial_key_r):
  33. full_key = partial_key_r**self.private_key
  34. full_key = full_key%self.public_key2
  35. self.full_key = full_key
  36. return full_key
  37. def encrypt_message(self, message):
  38. encrypted_message = ""
  39. key = self.full_key
  40. for c in message:
  41. encrypted_message += chr(ord(c)+key)
  42. return encrypted_message
  43. def decrypt_message(self, encrypted_message):
  44. decrypted_message = ""
  45. key = self.full_key
  46. for c in encrypted_message:
  47. decrypted_message += chr(ord(c)-key)
  48. return decrypted_message
  49. message="Hello, World!"
  50. a_public=197
  51. a_private=199
  52. b_public=151
  53. b_private=157
  54. Alex = DH_Endpoint(a_public, b_public, a_private)
  55. Elya = DH_Endpoint(a_public, b_public, b_private)
  56. a_partial=Alex.generate_partial_key()
  57. print(a_partial)
  58. b_partial=Elya.generate_partial_key()
  59. print(b_partial)
  60. a_full=Alex.generate_full_key(b_partial)
  61. print(a_full)
  62. b_full=Elya.generate_full_key(a_partial)
  63. print(b_full)
  64. b_encrypted=Elya.encrypt_message(message)
  65. print("Encrypted message: ",b_encrypted)
  66. message = Alex.decrypt_message(b_encrypted)
  67. print("Decrypted message:",message)