Search code examples
pythoncryptographydiffie-hellman

Cryptography Python: Diffie-Hellman key exchange implementation


Im currently trying to build an implementation of the Ephemeral Diffie-Hellman algorithm using the python cryptography module. It's important for our purposes that the users are authenticated. Both Alice and Bob have a public-private key pair and a certificate signed by a certificate authority to be able to verify their public key and link it to their identity.

Using Authenticated DH means that the sent messages (see image) will be signed using the above private key.

The documentation on DH using the python cryptography library can be found here: https://cryptography.io/en/latest/hazmat/primitives/asymmetric/dh/

However, I can not seem to understand what the described exchange function actually does. Is anyone able to explain to me where to situate it in the DH-algorithm? Preferably using the analogy of the following image:

DH-algorithm

Thanks in advance!


Solution

  • In their example (from the POV of Alice) the private_key is the orange paint, and peer_public_key is the light blue paint. shared_key is the brown paint at the end. That means of course that you need to do this twice, once for Bob, and once for Alice.

    Example code in python2:

    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import dh
    
    parameters = dh.generate_parameters(generator=2, key_size=512, backend=default_backend())
    
    a_private_key = parameters.generate_private_key()
    a_peer_public_key = a_private_key.public_key()
    
    b_private_key = parameters.generate_private_key()
    b_peer_public_key = b_private_key.public_key()
    
    a_shared_key = a_private_key.exchange(b_peer_public_key)
    b_shared_key = b_private_key.exchange(a_peer_public_key)
    
    print 'a_secret: '+a_shared_key
    print 'b_secret: '+b_shared_key