Skip to content

Instantly share code, notes, and snippets.

@schocco
Created June 5, 2012 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schocco/2871630 to your computer and use it in GitHub Desktop.
Save schocco/2871630 to your computer and use it in GitHub Desktop.
Public key encryption - Diffie–Hellman key exchange
# -*- coding: utf-8 -*-
'''
A very basic example for the Diffie–Hellman key exchange.
'''
class Machine(object):
'''
Represents a machine in the network
'''
def __init__(self, private_key, shared_keyset):
self.private_key = private_key
(self.pub_prime, self.pub_base) = shared_keyset
self.others_key = None
self.__shared_secret = None
def get_shared_secret(self):
'''
returns the shared secret
others pub_key ^ private_key modulo shared_prime = shared secret
'''
return self.others_key ** self.private_key % self.pub_prime
shared_secret = property(get_shared_secret)
def get_pub_key(self):
'''
returns the public key based on the private key and the shared keyset.
base ^ private_key modulo shared_prime = pubkey
'''
return self.pub_base ** self.private_key % self.pub_prime
def encrypt(self, message):
'''
encrypts a message using the private key and the shared secret
'''
cipher = ord(message) * self.shared_secret
return cipher
def decrypt(self, cipher):
'''
decrypts the message using the inverse shared secret
'''
message = cipher * self.shared_secret ** -1
return int(message)
# testrun
shared = (23,5)
alice = Machine(private_key=8, shared_keyset=shared)
bob = Machine(private_key=16, shared_keyset=shared)
alice.others_key = bob.get_pub_key()
bob.others_key = alice.get_pub_key()
cleartext = "k"
message_by_bob = bob.encrypt(cleartext)
decrypted_by_alice = alice.decrypt(message_by_bob)
print """
Bob encrypted the cleartext `%s` (value of %s).
The encrypted message `%s` was sent to Alice.
Alice then decrypted it to `%s`
""" % (cleartext, ord(cleartext), message_by_bob, chr(decrypted_by_alice))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment