Diffie Hellman key exchange protocol

Diffie Hellman key exchange protocol


Introduction

One of the fundamental challenges in cryptography is establishing a shared secret key between two parties communicating over a public channel.

While asymmetric encryption using public and private keys can solve this problem, it is often impractical to encrypt large volumes of data due to the high computational cost and key sizes involved.

A more efficient approach is to agree on a common symmetric key — typically shorter and faster to use, shared by both parties, from where comes the symmetric name — which can then be used for a secure communication.

The Diffie–Hellman key exchange protocol, introduced in 1976 by Whitfield Diffie and Martin Hellman, was the first practical method for two parties to securely establish a shared cryptographic key over an insecure channel — without any prior shared secrets [1].

Key note, in 1997 it was revealed that the mathematical foundations of this idea had been independently discovered earlier by James H. Ellis, Clifford Cocks, and Malcolm J. Williamson at the UK’s Government Communications Headquarters (GCHQ), but their work had remained classified until then [1].

What is the Diffie Hellman key exchange protocol

The Diffie Hellman key exchange protocol is a cryptographic method that allow two parties to securely establish a shared secret key, even if the the public medium that they are using is considered insecure.


This protocol does not takes care of encrypting the data itself, instead it is a key agreement protocol, allowing both parties to generate the same secret key independently, without transmitting the key itself. After the execution of this protocol, the shared key can then be used at symmetric encryption algorithms, such as the Advanced Encryption Standard (AES) to protect the confidentiality of the future communications.

At its core, this protocol relies on the mathematical properties of modular arithmetic and the difficulty of solving the discrete logarithm problem, that makes it computationally infeasible for the attackers to derive the shared secret from the intercepted data, during the exchanges of both parties involved in this protocol.

The Discrete Logarithm Problem (DLP) is a computational problem in modular arithmetic. It involves finding an integer x (the discrete logarithm) such that g^x = y mod p, where g, y, and p are known integers, and p is a prime number.

Where is it used

The Diffie Hellman key exchange protocol can be used for example in the following contexts:

  1. TLS/SSL (HTTPS): During the TLS handshake (initial phase of the protocol), this protocol can be used to agree on a symmetric session key.
  2. Messaging Applications: Applications such as Signal, WhatsApp and Telegram establish a secure channel between users, with a derivation of a symmetric key.
  3. Virtual Private Networks (VPNs): DH is used to setup a secure channel between the VPN client and the server.
  4. Encrypted File Transfer: Protocols such as STFP, SCP and SSH use DH during the handshake to negotiate keys for the encryption session.
  5. Custom protocol in Embedded systems: in resource constrained environments such as embedded systems, it can be used lightweight DH protocol variants such as Elliptic Curve DH that use smaller keys sizes, faster key generations still guaranteeing strong security.

How does it work

Here is the steps involved in the DH key exchange protocol [2]:

  1. Agreement on the public parameters: Alice and Bob agree on two public values. - A large prime number p - A primitive root (also called a generator) g. It is called primitive root because g ^ n mod p can generate every values in this range [1, p-1] for n ∈ [1, p-1] These values are not secret and be know by everybody. Example: Using RFC-3526 Modular Exponentiation Group with Prime modulus (MODP) group 17 with a prime number with a bit strength of 6144 bits, in hexadecimal [3]:

p = 0xFFFFFFFF FFFFFFFF C90FDAA2 
      2168C234 C4C6628B 80DC1CD1
      29024E08 8A67CC74 020BBEA6
      3B139B22 514A0879 8E3404DD
      EF9519B3 CD3A431B 302B0A6D
      F25F1437 4FE1356D 6D51C245
      E485B576 625E7EC6 F44C42E9
      A637ED6B 0BFF5CB6 F406B7ED
      EE386BFB 5A899FA5 AE9F2411
      7C4B1FE6 49286651 ECE45B3D
      C2007CB8 A163BF05 98DA4836
      1C55D39A 69163FA8 FD24CF5F
      83655D23 DCA3AD96 1C62F356
      208552BB 9ED52907 7096966D
      670C354E 4ABC9804 F1746C08
      CA18217C 32905E46 2E36CE3B
      E39E772C 180E8603 9B2783A2
      EC07A28F B5C55DF0 6F4C52C9
      DE2BCBF6 95581718 3995497C
      EA956AE5 15D22618 98FA0510
      15728E5A 8AAAC42D AD33170D
      04507A33 A85521AB DF1CBA64
      ECFB8504 58DBEF0A 8AEA7157
      5D060C7D B3970F85 A6E1E4C7
      ABF5AE8C DB0933D7 1E8C94E0
      4A25619D CEE3D226 1AD2EE6B
      F12FFA06 D98A0864 D8760273
      3EC86A64 521F2B18 177B200C
      BBE11757 7A615D6C 770988C0
      BAD946E2 08E24FA0 74E5AB31
      43DB5BFC E0FD108E 4B82D120
      A9210801 1A723C12 A787E6D7
      88719A10 BDBA5B26 99C32718
      6AF4E23C 1A946834 B6150BDA
      2583E9CA 2AD44CE8 DBBBC2DB
      04DE8EF9 2E8EFC14 1FBECAA6
      287C5947 4E6BC05D 99B2964F
      A090C3A2 233BA186 515BE7ED
      1F612970 CEE2D7AF B81BDD76
      2170481C D0069127 D5B05AA9
      93B4EA98 8D8FDDC1 86FFB7DC
      90A6C08F 4DF435C9 34028492
      36C3FAB4 D27C7026 C1D4DCB2
      602646DE C9751E76 3DBA37BD
      F8FF9406 AD9E530E EE5DB382
      F413001A EB06A53E D9027D83
      1179727B 0865A891 8DA3EDBE
      BCF9B14E D44CE6CB ACED4BB1
      BDB7F144 7E6CC254 B3320515
      12BD7AF4 26FB8F40 1378CD2B
      F5983CA0 1C64B92E CF032EA1
      5D1721D0 3F482D7C E6E74FEF
      6D55E702 F46980C8 2B5A8403
      1900B1C9 E59E7C97 FBEC7E8F
      323A97A7 E36CC88B E0F1D45B
      7FF585AC 54BD407B 22B4154A
      ACC8F6D7 EBF48E1D 814CC5ED
      20F8037E 0A79715E EF29BE32
      806A1D58 BB7C5DA7 6F550AA3
      D8A1FBFF 0EB19CCB 1A313D55
      CDA56C9E C2EF2963 2387FE8D
      76E3C046 8043E8F6 63F4860E
      E12BF2D5 B0B7474D 6E694F91 
      E6DCC402 4FFFFFFF FFFFFFFF
      F

g = 0x02        

2. Private key selection by both parties: both parties generate a private key, with the following requirements: a, b ∈ [2, p-1[ those values are never shared. Alice randomly selects a such that: 1 < a < p - 1 Bob randomly selects b such that: 1 < b < p - 1 These values are generated using a cryptographic secure pseudo random number generator (CSPRNG) to avoid predictability.

3. Public key computation: after each party as decide on their private key, the next step is to compute the public key, that will be shared over the network. Formula: Each party computes their public key using the following formula

publicKey = g ^ privateKey mod p        

where ^ stands for modular exponentiation.

Alice: A = g ^ a mod p

Bob:   B = g ^ b mod p        

4. Shared key computation: once both parties have received the public key from the other person involved in the communication, they can use that information in conjunction with their secret key to derive a shared secret.

This shared secret is derived independently by both parties and is never transmitted over the internet.

Formula: Each party computes the shared secret using the following formula

sharedSecret = otherPartyPublicKey ^ privateKey mod p        

Continuing the setup of the protocol with Alice and Bob as an example:

- Alice sends A public key to Bob and computes:

s = B ^ a mod p        

- Bob send B public key to Alice and computes:

s = A ^ b mod p        

Where:

A = g ^ a mod p is Alice's public key

B = g ^ b mod p is Bob's public key

p is the shared large prime

a, b are private keys of Alice and Bob respectively

This works because:

Alice: s = B ^ a mod p = (g ^ b mod p) ^ a mod p = g ^ (ab) mod p 

Bob:   s = A ^ b mod p = (g ^ a mod p) ^ b mod p = g ^ (ab) mod p        

by means of the modular exponentiation rules and equivalencies.

The shared secret is a number modulo p, so its maximum size is equal to the size of p, so its size depends on the Diffie Hellman group where the generator g and the prime p are agreed beforehand.


Here is a brief resume of the several DH groups that can be used in the DH key exchange protocol, table 1 [3]:

Public parameters group info used in the Diffie Hellman Key exchange
Table 1: Group information commonly used in the Diffie Hellman key exchange, regarding the public parameter prime p

As we can see the shared secret size can vary from the 2048 bit size until the 8192 bits, depending on the security requirements involved, this size is not practical to use in a symmetrical encryption setup, so what is done in practice is to pass the share secret through a Key derivation Function (KDF) such as SHA-256 to produce a fixed size symmetric key, for example a 256 bit that can be used in a symmetric encryption AES.

So although the raw shared secret may be hundreds of bytes, the final encryption key is often 128, 192 or 256 bits long, depending on requirements of the symmetric encryption been used.

Example for a 256 bit secret key generation:

finalSymmetricKey = SHA-256(rawSharedSecret)        

In practice more information is added to the step above, to derive the final symmetric key , such as nonce's (random single-use values) from both parties, to prevent replay attacks.

Example for a 256 bit secret key generation, more realistic:

finalSymmetricKey = SHA-256(rawSharedSecret || Nc || Ns)        

Where:

  • Nc - nonce created by the client
  • Ns - nonce created by the server

Example of the DH key exchange protocol with small numbers:

In this section it will be depicted a small example of the DH key exchange protocol with small numbers to allow easier calculations:

Public parameters commonly agreed upon:

Prime number: p = 23

Generator: g = 5

Alice side:

  • She generates her private key randomly, a = 6 such as 1 < a < p - 1
  • She computes her public key: A = g ^ a mod p <=> A = 5 ^ 6 mod 23 <=> A = 8

Bob side:

  • He generates his private key randomly, b = 15 such as 1 < b < p - 1
  • She computes her public key: B = g ^ b mod p <=> B = 5 ^ 15 mod 23 <=> B = 19

Shared secret computation:

Alice sends her public key A and the nonce = 12 to Bob.

Bob sends his public key B and the nonce = 34 to Alice.

Alice side: s = B ^ a mod p <=> s = 19 ^ 6 mod 23 <=> s = 2

Bob side: s = A ^ b mod p <=> s = 8 ^ 15 mod 23 <=> s = 2

Secret key derivation:

Having both arrived at the same shared secret, and having both the nonce's of each party, using as an example for the KDF the SHA-256, if we consider Bob as the client and Alice as the server (assuming 32 bit nonce's):

finalSymmetricKey = SHA-256(rawSharedSecret || Nc || Ns) 

finalSymmetricKey = SHA-256(rawSharedSecret || N bob || N alice)

finalSymmetricKey = SHA-256(2 || 34 || 12)

finalSymmetricKey = SHA-256(0x00000002 || 0x00000022 || 0x0000000C)

finalSymmetricKey (hex) = 8d9061cf44be8f8685611c7176db1bbd0b01ae23ff2eddbe407f577a0b9cf011        

So the server, in this case Alice, could generate an unique identifier for each session created, saving all the data required for that session, here is an example where the server creates two independent sessions for the user Bob, generating for each of them a unique session id with his own symmetric private encryption key:

{
  "8b8daea1-7a09-48ce-b19c-0741b7d5a58e": {
    "iv": "27f4cb54f458293c916c3da73f633dfc",
    "derivedKey": "7c7994af8217cc2f462efd7e1973c65d064d2be15ce61e34e5b45e9fb1bf595b",
    "serverNonce": "e33ff436e8ada1e26108a587b38e7607",
    "clientNonce": "f5c6a5371abd9f63c3e5094900b05c30",
    "clientId": "Bob",
    "sessionId": "8b8daea1-7a09-48ce-b19c-0741b7d5a58e"
  },
  "6ab6f667-9a53-4667-a471-f9568dece71c": {
    "iv": "09738f5a7479737340efa17bfc5729d4",
    "derivedKey": "d8c60a9be0f5a1a65de209eeb025e7f34e36f9e1131e1a920b18c0c50c09e8f6",
    "serverNonce": "57c11f1d76296669e7e465bdd93fc553",
    "clientNonce": "28d83b693d19afc0a42ccc9278140a50",
    "clientId": "Bob",
    "sessionId": "6ab6f667-9a53-4667-a471-f9568dece71c"
  }
}        

Why is this protocol considered secure:

The DH key exchange protocol is considered secure because it relies on the computational difficulty of solving the Discrete Logarithm Problem (DLP).

The security of the DH key exchange protocol relies on the fact that it is very hard to find the private exponent (the "secret") from the public values exchanged, when the prime p is a very large number, 2048 bits or more.

The eavesdropper's challenge, considering an eavesdropper (Eve) observes p, g, A and B exchanged by two parties. To find Alice's private key a from g, p, and A, Eve would have to solve the equation:

A = g^a mod p  , solving for a

a = log₍g₎ A mod p            

This is known as the Discrete Logarithm Problem, for sufficiently large primes p (e.g. 2048 bits or more) there is no known efficient algorithm to solve this problem in a reasonable amount of time, even with classic supercomputers.

While classical Diffie-Hellman is highly secure against current, classical computers, it is fundamentally vulnerable to attacks by future, sufficiently powerful quantum computers running Shor's algorithm [4]. The global cryptographic community is actively developing and deploying new "post-quantum" algorithms to address this future threat [5].

DH key exchange protocol implementation:

In this section it is presented a practical implementation of the DH key exchange protocol, in this example the public parameters p and g are picked from the MODP groups present in the RFC3526 [3], each party generates a nonce for each session created, here is the class diagram of this solution, figure 1.

Class diagram of a proof of concept of the Diffie Hellman key exchange protocol
Figure 1: Diffie Hellman's key exchange protocol class diagram.

As we can see in figure 1, the communication between the client and the server is done via HTTP requests, both parties use the same software classes to perform the protocol, and it is the client that has the initiative on this protocol.

Important also to mention that the server exposes two endpoints, one to execute the DH key exchange protocol via the POST /keyExchange, and the other endpoint allows to retrieve all the session keys created on the server side via the GET /sessionsData.

The sequence diagram of this protocol is shown next, figure 2, where it is possible to see the symmetric of the actions taken by both parties in this protocol, a cipher text message is also included in the server's response to the clients request, to allow the confirmation on the client side that the protocol execution when well on the server side.

Sequence diagram of the Diffie Hellman key exchange protocol implementation
Figure 2: Sequence diagram of this implementation of the Diffie Hellman Key exchange

Here is an example of the output of the endpoint GET /sessionsData after three clients have performed the DH key exchange protocol with the server, figure 3.

Example of the output information of the endpoint GET /sessionsData
Figure 3: Example of the output information of the endpoint GET /sessionsData.

Here is a follows a quick demo of this implementation, first the server started, then several clients will try to perform the DH key exchange protocol with that server, in the end the endpoint GET /sessionsData will the triggered to confirm the correct setup of the sessions with each connection by those clients.

Video 1: Demo of the DH key exchange protocol between a server and three clients.

Conclusion:

The Diffie-Hellman (DH) key exchange protocol, since its creation in 1976, has served as a reference of secure digital communication. As demonstrated in this article through its fundamental mathematical principles—relying on the computational difficulty of the Discrete Logarithm Problem (DLP) — DH effectively enables two parties to establish a shared secret key over an insecure channel, without any prior shared knowledge.

This implementation of a practical client-server shows its efficiency in establishing cryptographic session keys, essential for secure data exchange.

However, the reality of cryptographic security is rapidly evolving. While robust against all known classical computational attacks, the advent of sufficiently powerful quantum computers poses an existential threat to the security guarantees of Diffie-Hellman and other widely used public-key cryptographic algorithms like RSA and Elliptic Curve Cryptography (ECC) that requires urgent attention in the coming times.


Implementation source code:

https://github.com/Photon-einstein/Cryptopals/tree/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_33

References:

[1] Diffie–Hellman key exchange. Wikipedia, The Free Encyclopedia. Wikipedia Foundation, Inc., 18 June 2025. Web. 18 June 2025. https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange.

[2] Diffie, W., & Hellman, M. E. (1976). New directions in cryptography. IEEE Transactions on Information Theory, 22(6), 644–654. https://doi.org/10.1109/TIT.1976.1055638

[3] D. Kivinen and H. Krawczyk, "More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)," IETF RFC 3526, May 2003. Available: https://datatracker.ietf.org/doc/html/rfc3526.

[4] Shor, P. W. (1994). Polynomial-Time Algorithms for Prime Factorization and Discrete Logarithms on a Quantum Computer. Proceedings of the 35th Annual Symposium on Foundations of Computer Science. IEEE, pp. 124-134.

[5] Bernstein, D. J., & Lange, T. (2017). "Post-quantum cryptography." Nature, 549(7671), 188-194.

To view or add a comment, sign in

Others also viewed

Explore content categories