Guest User

Untitled

a guest
Oct 17th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. '''
  3. A very basic example for the Diffie–Hellman key exchange.
  4. '''
  5.  
  6. class Machine(object):
  7. '''
  8. Represents a machine in the network
  9. '''
  10. def __init__(self, private_key, shared_keyset):
  11. self.private_key = private_key
  12. (self.pub_prime, self.pub_base) = shared_keyset
  13. self.others_key = None
  14. self.__shared_secret = None
  15.  
  16. def get_shared_secret(self):
  17. '''
  18. returns the shared secret
  19.  
  20. others pub_key ^ private_key modulo shared_prime = shared secret
  21. '''
  22. return self.others_key ** self.private_key % self.pub_prime
  23.  
  24. shared_secret = property(get_shared_secret)
  25.  
  26. def get_pub_key(self):
  27. '''
  28. returns the public key based on the private key and the shared keyset.
  29.  
  30. base ^ private_key modulo shared_prime = pubkey
  31. '''
  32. return self.pub_base ** self.private_key % self.pub_prime
  33.  
  34. def encrypt(self, message):
  35. '''
  36. encrypts a message using the private key and the shared secret
  37. '''
  38. cipher = ord(message) * self.shared_secret
  39. return cipher
  40.  
  41. def decrypt(self, cipher):
  42. '''
  43. decrypts the message using the inverse shared secret
  44. '''
  45. message = cipher * self.shared_secret ** -1
  46. return int(message)
  47.  
  48. # testrun
  49. shared = (23,5)
  50.  
  51. alice = Machine(private_key=8, shared_keyset=shared)
  52. bob = Machine(private_key=16, shared_keyset=shared)
  53.  
  54. alice.others_key = bob.get_pub_key()
  55. bob.others_key = alice.get_pub_key()
  56.  
  57. cleartext = "k"
  58. message_by_bob = bob.encrypt(cleartext)
  59. decrypted_by_alice = alice.decrypt(message_by_bob)
  60.  
  61. print """
  62. Bob encrypted the cleartext `%s` (value of %s).
  63. The encrypted message `%s` was sent to Alice.
  64. Alice then decrypted it to `%s`
  65. """ % (cleartext, ord(cleartext), message_by_bob, chr(decrypted_by_alice))
Add Comment
Please, Sign In to add comment