<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tiago Sousa</title>
    <description>The latest articles on DEV Community by Tiago Sousa (@tiago_sousa_4baece16501be).</description>
    <link>https://dev.to/tiago_sousa_4baece16501be</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2310589%2Fc2c3bf1d-b8d2-46c0-97e5-2dcde08130da.jpg</url>
      <title>DEV Community: Tiago Sousa</title>
      <link>https://dev.to/tiago_sousa_4baece16501be</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tiago_sousa_4baece16501be"/>
    <language>en</language>
    <item>
      <title>Secure Remote Password (SRP) protocol</title>
      <dc:creator>Tiago Sousa</dc:creator>
      <pubDate>Tue, 28 Oct 2025 20:21:16 +0000</pubDate>
      <link>https://dev.to/tiago_sousa_4baece16501be/secure-remote-password-srp-protocol-18oj</link>
      <guid>https://dev.to/tiago_sousa_4baece16501be/secure-remote-password-srp-protocol-18oj</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this article, I’ll walk you through my implementation of the Secure Remote Password (SRP) [1] protocol, including its challenges, architecture, and testing strategies. You can find the full source code on my &lt;a href="https://github.com/Photon-einstein/Cryptopals/tree/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The Secure Remote Password (SRP) protocol is a type of password-authenticated key exchange (PAKE) protocol that has been specifically designed to avoid conflicts with existing patents. It falls under the category of augmented PAKE protocols, which offer enhanced security properties compared to traditional password-based systems.&lt;/p&gt;

&lt;p&gt;As with all PAKE protocols, SRP ensures that an attacker who intercepts communication between the client and server cannot gather enough information to guess the password through brute force or dictionary attacks. This is because the protocol requires additional interactions for each password guess, making such attacks impractical. Moreover, since SRP is an augmented PAKE, the server does not store any data that is equivalent to the password. This means that even if an attacker gains access to the server's database, they cannot impersonate the client unless they first perform a computationally expensive brute-force search to recover the password.&lt;/p&gt;

&lt;p&gt;In simpler terms, SRP allows a user (the "client") to prove to a server that they know their password without ever transmitting the password itself or any data that could be used to reconstruct it. The password remains securely on the client side and is never shared with the server. The server, on the other hand, stores only a "verifier," which is a cryptographic representation of the password that cannot be reversed to reveal the original password.&lt;/p&gt;

&lt;p&gt;Additionally, SRP provides mutual authentication. The server must also prove its legitimacy to the client, ensuring that the client is not connecting to a malicious or fake server. This feature helps protect users from phishing attacks without requiring them to analyze complex URLs or other indicators of legitimacy [2].&lt;/p&gt;

&lt;p&gt;SRP's primary mathematically proven security property is its equivalence to the Diffie-Hellman protocol when facing a passive attacker. While SRP is a mature and widely used protocol, it is based on an older design that has shown some subtle weaknesses in certain variants. For example, SRP is not universally composable (UC-secure), does not fully resist all precomputation attacks, has less robust formal security proofs, and lacks protection against some modern attack scenarios. &lt;/p&gt;

&lt;p&gt;As a result, SRP is now considered somewhat outdated. Modern alternatives have emerged, such as OPAQUE, which is the preferred augmented PAKE protocol, and CPace or SPAKE2, which are better suited for balanced PAKE scenarios where both parties share the password. These newer protocols address many of the limitations found in SRP and are designed to meet the demands of contemporary security models [2].&lt;/p&gt;

&lt;p&gt;Even so a detailed study of SRP protocol and its implementation is considered a good learning exercise as I will try to show.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ins and outs of SRP protocol
&lt;/h2&gt;

&lt;p&gt;SRP leverages the computational difficulty of the discrete logarithm problem. Both client and server perform complex mathematical operations involving large prime numbers, generating ephemeral keys and shared secrets that prove knowledge without revelation. The protocol ensures that even if someone intercepts all network traffic, they gain no advantage in discovering the client's password.&lt;/p&gt;

&lt;p&gt;The result is an authentication that's both more secure and more private than anything passwords alone can provide.&lt;/p&gt;

&lt;p&gt;There are two phases in the SRP protocol. &lt;/p&gt;

&lt;p&gt;In the first phase the user makes the &lt;strong&gt;registration&lt;/strong&gt; in the server, afterwards he can perform the &lt;strong&gt;authentication&lt;/strong&gt; whenever he needs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Registration at the SRP protocol
&lt;/h3&gt;

&lt;p&gt;The registration process in the SRP serves &lt;strong&gt;one fundamental purpose: to establish a mathematical relationship that enables future authentication without ever requiring password transmission or storage&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The goal of the registration process is to the client and the server come into an agreement about the group parameters, namely the big prime number N and the generator g. Also in this phase the client defines the password and sends it to the server its verifier, without exposing by itself the password, figure 1.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcly29nnne5z71br7k6yx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcly29nnne5z71br7k6yx.png" alt="Figure 1: Registration process at the SRP protocol." width="594" height="609"&gt;&lt;/a&gt;&lt;br&gt;
Figure 1: Registration process at the SRP protocol.&lt;/p&gt;

&lt;p&gt;Initially the client identifies itself by its username (U) and optionally the requested group ID, the server generates a cryptographically secure, unique per user, random salt and returns also the required N and g from the group ID that ensures the minimum level of security that is acceptable at the server side.&lt;/p&gt;

&lt;p&gt;The N and g parameters are chosen according to the group ID defined at the RFC-5054, where the ID 1 correspond to the minimum security level with a smaller prime N (1024 bits size) and the group ID 7 correspond to the the maximum security level with the greater prime N (8192 bits size).&lt;/p&gt;

&lt;p&gt;Full information of the groups ID defined at RFC-5054 can be found in this json file used in this implementation.&lt;/p&gt;

&lt;p&gt;With a greater group ID, the size of the prime will increase and the hash algorithm will be more complex, that will bring more security but at the cost of extra computation every time this protocol needs to be executed.&lt;/p&gt;

&lt;p&gt;After the successful conclusion of the registration process at the SRP protocol the client will have the corresponding salt of that session, and also the given N and g parameters from the required group ID to be used at the SRP protocol with that server. &lt;/p&gt;

&lt;p&gt;At the server side, he will have the salt s generated for that given user U, and also the verifier of the password v.&lt;/p&gt;
&lt;h3&gt;
  
  
  Authentication of the SRP protocol
&lt;/h3&gt;

&lt;p&gt;The authentication process in SRP serves one fundamental purpose: to enable mutual verification of identity between client and server without transmitting the password or any password-equivalent data.&lt;/p&gt;

&lt;p&gt;Here is the communication flow between the client and the server at the authentication using the SRP protocol, figure 2:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F476tawh25jlzpe3aqhhs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F476tawh25jlzpe3aqhhs.png" alt="Figure 2: Authentication process at the SRP protocol [1]." width="800" height="592"&gt;&lt;/a&gt;&lt;br&gt;
Figure 2: Authentication process at the SRP protocol [1].&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Primary Objectives:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Zero-Knowledge Password Verification&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The authentication process allows the client to prove he knows the password without transmitting the password over the network, revealing any information that could be used to recover the password, giving the server access to password-equivalent data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mutual Authentication:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Unlike traditional password systems, SRP authentication provides bidirectional verification:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Client authenticates to Server&lt;/strong&gt;: "I know my password" (via M proof)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Server authenticates to Client&lt;/strong&gt;: "I have your legitimate verifier" (via M2 proof)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Secure session establishment:&lt;br&gt;
The authentication process generates a shared session key (K) that both parties can compute independently:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client: S = (B - k * g^x) ^ (a + u * x) mod N  

Server: S = (A * v^u)^b mod N
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementation Details of the SRP protocol
&lt;/h2&gt;

&lt;p&gt;The SRP protocol was implemented in C++, using the HTTP requests library from Crow and regarding the big number arithmetic, it was used the services available at the OpenSSL.&lt;/p&gt;

&lt;p&gt;OpenSSL provides cryptographic primitives such as hashing (SHA-1, SHA-256, etc.) and big integer arithmetic (via BIGNUM), ensuring compliance with cryptographic standards and avoids reinventing the wheel for low-level operations.&lt;/p&gt;

&lt;p&gt;The HTTP server Implements the SRP protocol as a web service with endpoints for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;registration&lt;/strong&gt; (/srp/register/init, /srp/register/complete);&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;authentication&lt;/strong&gt; (/srp/auth/init, /srp/auth/complete);&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this way the clients interact with the server over HTTP, simulating real-world use cases.&lt;/p&gt;

&lt;p&gt;The validation of the protocol was performed against python scripts used to cross-validate the C++ implementation against RFC 5054 [1] test vectors, ensuring correctness of key computations (e.g., x, v, S, K, M, M2) by comparing results from both implementations. &lt;/p&gt;

&lt;p&gt;The unit tests in C++ also validate all the intermediate results against the RFC 5054 [1] test vectors.&lt;/p&gt;

&lt;h3&gt;
  
  
  Architecture decisions
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Modular Design&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To manage the complexity of the SRP protocol, it was adopted a modular and extensible architecture, namely:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Client Class&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Handles the client-side computations (e.g., A, x, S, K, M).&lt;/li&gt;
&lt;li&gt;Manages the registration and authentication flows from the client’s perspective.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Server Class:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Handles the server-side computations (e.g., B, S, M2).&lt;/li&gt;
&lt;li&gt;Manages user sessions and validates client proofs during authentication.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;SecureRemotePassword Class:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Encapsulates the SRP protocol logic, including cryptographic operations and parameter validation.&lt;/li&gt;
&lt;li&gt;Acts as the core engine for both the client and server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;SessionData Class:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Manages session-specific data (e.g., ephemeral keys, group parameters, and state).&lt;/li&gt;
&lt;li&gt;Ensures that each session is isolated and stateless between requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;SrpParametersLoader:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Loads SRP group parameters (e.g., N, g) from a JSON file (SrpParameters.json).&lt;/li&gt;
&lt;li&gt;Supports multiple groups (1024-8192 bits) as defined in RFC 5054 [1].&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;EncryptionUtility:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Provides helper functions for hashing, big integer operations, and padding.&lt;/li&gt;
&lt;li&gt;Abstracts cryptographic details, making the code more readable and maintainable.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Multi-Group Support:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The implementation supports multiple SRP groups, allowing flexibility in cryptographic strength, accordingly to the server requirements in terms of security:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Groups Supported:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1024-bit (Group 1)&lt;/li&gt;
&lt;li&gt;1536-bit (Group 2)&lt;/li&gt;
&lt;li&gt;2048-bit (Group 3)&lt;/li&gt;
&lt;li&gt;3072-bit (Group 4)&lt;/li&gt;
&lt;li&gt;4096-bit (Group 5)&lt;/li&gt;
&lt;li&gt;6144-bit (Group 6)&lt;/li&gt;
&lt;li&gt;8192-bit (Group 7)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It exists a multi group support because different applications may require different levels of security. Smaller groups (e.g., 1024-bit) are faster but less secure, while larger groups (e.g., 8192-bit) provide stronger security at the cost of performance.&lt;/p&gt;

&lt;p&gt;Group parameters (N, g) are loaded dynamically from SrpParameters.json. The client and server negotiate the group during the registration phase.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multiple Hash Algorithms:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To ensure flexibility and compliance with RFC 5054 [1], it was included support for multiple hash algorithms,. namely:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SHA-1 (to validate against the RFC 5054 [1] test vectors) &lt;/li&gt;
&lt;li&gt;SHA-256&lt;/li&gt;
&lt;li&gt;SHA-384&lt;/li&gt;
&lt;li&gt;SHA-512&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Different systems and applications may require different hash algorithms based on security policies, as the requirements of each group varies in relation to the hash algorithms.&lt;/p&gt;

&lt;p&gt;SHA-1 is included for compatibility with RFC 5054 [1] test vectors, but stronger hashes (e.g., SHA-256, SHA-512) are recommended for modern systems.&lt;/p&gt;

&lt;p&gt;Hash functions are abstracted in the EncryptionUtility class. The hash algorithm is negotiated during the registration phase and stored as part of the session.&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture Highlights
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;registration flow&lt;/strong&gt; is composed of these requests by the client:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;/srp/register/init&lt;/strong&gt;: The client requests SRP parameters (e.g., N, g, salt) from the server;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;/srp/register/complete&lt;/strong&gt;: The client sends the computed verifier (v) to the server, which stores it for future authentication.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the registration proceeds until completion then the client is then able to perform the authentication with the server afterwards.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;authentication flow&lt;/strong&gt; is implemented as two HTTP endpoints:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;/srp/auth/init&lt;/strong&gt;: The client sends its username (U) to the server. The server responds with s, B, and groupId.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;/srp/auth/complete&lt;/strong&gt;: The client sends A and M to the server. The server validates M and responds with M2 for mutual authentication.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Both client and server compute the shared secret S independently. The session key K = H(S) is derived for secure communication.&lt;/p&gt;

&lt;p&gt;The Class diagram of the implementation of the SRP protocol is available at the figure 3:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/uml_diagrams/Secure_Remote_Password_class_diagram.svg" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7vtadfpslhkx8jnobpj.png" alt="Figure 3: Class diagram of the SRP protocol implementation" width="800" height="329"&gt;&lt;/a&gt;&lt;br&gt;
Figure 3: Class diagram of the SRP protocol implementation&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/uml_diagrams/SRP_implementation_sequence_diagram.svg" rel="noopener noreferrer"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpd3r7i6ndae47pyb6qlx.png" alt="Figure 4: Sequence diagram of the SRP protocol implementation" width="800" height="1101"&gt;&lt;/a&gt;&lt;br&gt;
Figure 4: Sequence diagram of the SRP protocol implementation&lt;/p&gt;
&lt;h2&gt;
  
  
  Testing &amp;amp; Validation Strategy
&lt;/h2&gt;

&lt;p&gt;Testing and validation were critical to ensuring the correctness, security, and compliance the SRP implementation with RFC 5054[1]. A multi-layered approach was adopted to cover all aspects of the protocol, from individual components to full end-to-end flows.&lt;/p&gt;
&lt;h3&gt;
  
  
  Unit Tests: Test cases across all Components
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/Photon-einstein/Cryptopals/tree/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/tests" rel="noopener noreferrer"&gt;Unit testing&lt;/a&gt; was the foundation of the validation strategy. Each component of the SRP protocol was tested in isolation to ensure correctness and robustness.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Areas Covered:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mathematical Operations: Modular exponentiation, padding, and big integer arithmetic using OpenSSL's BIGNUM.&lt;/li&gt;
&lt;li&gt;Hashing Functions: Validation of SHA-1, SHA-256, SHA-384, and SHA-512 wrappers.&lt;/li&gt;
&lt;li&gt;Parameter Validation: Ensuring constraints like 1 &amp;lt; A &amp;lt; N and 1 &amp;lt; B &amp;lt; N are enforced.&lt;/li&gt;
&lt;li&gt;Session Management: Testing the SessionData class for proper state handling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example Test Cases:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Verifying that calculateU produces the correct scrambling parameter u for given inputs.&lt;/li&gt;
&lt;li&gt;Ensuring calculateX correctly derives the private key x from the salt, username, and password.&lt;/li&gt;
&lt;li&gt;Validating calculateV to ensure the verifier v matches RFC 5054[1] test vectors.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  RFC Vector Testing: Validation Against Official Test Vectors:
&lt;/h3&gt;

&lt;p&gt;To ensure compliance with the SRP protocol as defined in RFC 5054 [1], the implementation was tested against the official test vectors provided in the specification.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test Vector input parameters:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Username&lt;/strong&gt;: "alice"&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Password&lt;/strong&gt;: "password123"&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Salt&lt;/strong&gt;: "BEB25379D1A8581EB5A727673A2441EE"&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Group&lt;/strong&gt;: 1024-bit (Group 1)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hash Algorithm&lt;/strong&gt;: SHA-1&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Private key a&lt;/strong&gt;: "60975527035CF2AD1989806F0407210BC81EDC04E2762A56AFD529DDDA2D4393"&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Private key b&lt;/strong&gt;: "E487CB59D31AC550471E81F00F6928E01DDA08E974A004F49E61F5D105284D20"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Validate Outputs:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Public keys (A, B)&lt;/li&gt;
&lt;li&gt;Scrambling parameter (u)&lt;/li&gt;
&lt;li&gt;Shared secret (S)&lt;/li&gt;
&lt;li&gt;Session key (K)&lt;/li&gt;
&lt;li&gt;Intermediate results: (k, x)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All computed values matched the RFC 5054 [1] test vectors, confirming the correctness the implementation, these test vector were essential to confirm the entire correctness of this implementation.&lt;/p&gt;
&lt;h3&gt;
  
  
  Cross-Language Validation: Python scripts for mathematical verification
&lt;/h3&gt;

&lt;p&gt;To further validate the correctness of the C++ implementation, Python scripts were used to cross-check key computations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python Validation Scripts:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateX.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateX.py&lt;/strong&gt;&lt;/a&gt;: Validates the private key x.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateV.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateV.py&lt;/strong&gt;&lt;/a&gt;: Validates the verifier v.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateSClient.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateSClient.py&lt;/strong&gt;&lt;/a&gt; and &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateSServer.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateSServer.py&lt;/strong&gt;&lt;/a&gt;: Validate the shared secret S on both client and server sides.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateM.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateM.py&lt;/strong&gt;&lt;/a&gt; and &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateM2.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateM2.py&lt;/strong&gt;&lt;/a&gt;: Validate the client and server proofs.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculate_k_MultiplierParameter.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculate_k_MultiplierParameter.py&lt;/strong&gt;&lt;/a&gt; : Verifies the correctness of the multipliers k for each group.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateK.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateK.py&lt;/strong&gt;&lt;/a&gt;: Validates the Key generation K.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculatePublicKey.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculatePublicKey.py&lt;/strong&gt;&lt;/a&gt;: Validates the public key generation A and B.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/calculateU.py" rel="noopener noreferrer"&gt;&lt;strong&gt;calculateU.py&lt;/strong&gt;&lt;/a&gt;: Validates the parameter u calculation.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/testScripts/testSRP_withRFC_vector.py" rel="noopener noreferrer"&gt;&lt;strong&gt;testSRP_withRFC_vector.py&lt;/strong&gt;&lt;/a&gt;: Test that the S at the client and server match with RFC-5054 test vectors.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Python’s simplicity and precision in handling big integers made it ideal for cross-referencing results. The scripts served as a secondary implementation to catch potential bugs in the C++ code during the development.&lt;/p&gt;
&lt;h3&gt;
  
  
  Integration Testing: Full Protocol Flows
&lt;/h3&gt;

&lt;p&gt;Integration tests were designed to validate the entire SRP protocol flow, from registration to authentication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tested flow:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Registration&lt;/strong&gt;: Ensuring the client computes v correctly and the server stores it securely.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication&lt;/strong&gt;: Verifying that both client and server compute the same shared secret S and session key K.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Edge cases:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Invalid usernames or passwords.&lt;/li&gt;
&lt;li&gt;Mismatched group parameters (N, g).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Manual Testing: Curl Commands for Endpoint Validation
&lt;/h3&gt;

&lt;p&gt;Manual testing was performed using curl's to simulate client-server interactions and validate the HTTP endpoints.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Endpoints Tested:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;/srp/register/init&lt;/strong&gt;: Validates the server’s response with group parameters and salt.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;/srp/register/complete&lt;/strong&gt;: Ensures the server correctly stores the verifier.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;/srp/auth/init&lt;/strong&gt;: Validates the server’s generation of B and response to the client.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;/srp/auth/complete&lt;/strong&gt;: Ensures mutual authentication and session key derivation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example curl command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X POST http://localhost:18080/srp/auth/init \
-H "Content-Type: application/json" \
-d '{
  "clientId": "alice"
}' | jq
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This multi-layered approach to testing and validation was essential to build a robust and standards-compliant SRP implementation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lessons Learned &amp;amp; Best Practices
&lt;/h2&gt;

&lt;p&gt;Implementing the Secure Remote Password (SRP) protocol from scratch was both a challenging and rewarding experience. Along the way, I encountered several key insights and developed best practices that are applicable not only to SRP but to cryptographic implementations in general.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mathematical Precision is Crucial
&lt;/h3&gt;

&lt;p&gt;Cryptographic protocols like SRP rely heavily on precise mathematical operations. Even small errors in modular arithmetic, padding, or hashing can lead to incorrect results or security vulnerabilities.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Always validate intermediate results against known test vectors (e.g., RFC 5054 [1]).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Use well-tested libraries like OpenSSL for low-level operations (e.g., BIGNUM) instead of implementing them from scratch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cross-Validation Saves Time
&lt;/h3&gt;

&lt;p&gt;Cross-language validation was invaluable in catching subtle bugs. Python scripts were used to verify the correctness of key computations (e.g., x, v, S, K) against the C++ implementation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: A secondary implementation in a simpler language (like Python) can help identify discrepancies early.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Write small, focused scripts to validate each step of the protocol independently.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Comprehensive Testing is Essential
&lt;/h3&gt;

&lt;p&gt;Testing was the backbone of this implementation. From unit tests to integration tests, every component was rigorously validated, this was the solution to handle the complexity of the protocol.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Cryptographic protocols require more than just functional testing; they need validation against edge cases and compliance with standards.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Use official test vectors (e.g., RFC 5054 [1]) to ensure compliance.Test with multiple group sizes (1024-bit to 8192-bit) and hash algorithms (SHA-1 to SHA-512). Include negative tests (e.g., invalid inputs, mismatched parameters).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Modular Design Simplifies Complexity
&lt;/h3&gt;

&lt;p&gt;SRP is a complex protocol with multiple moving parts (registration, authentication, cryptographic computations). A modular design made it easier to manage and debug.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Breaking the implementation into smaller, reusable components (e.g., Client, Server, SecureRemotePassword) reduces complexity and improves maintainability.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Follow the single responsibility principle—each class or module should handle one specific aspect of the protocol.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Documentation is key for maintainability
&lt;/h3&gt;

&lt;p&gt;Cryptographic protocols are inherently complex, and maintaining clarity is critical. Detailed documentation, including UML diagrams, helped keep the implementation organized and understandable to onboard future developers and manage complexity.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Clear documentation is as important as the code itself, especially for protocols with intricate flows like SRP.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Use UML diagrams to visualize class relationships and sequence flows. Document every step of the protocol, including assumptions, constraints, and edge cases.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Security is Non-Negotiable
&lt;/h3&gt;

&lt;p&gt;SRP is designed to be secure, but the implementation must also follow best practices to avoid introducing vulnerabilities.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Security is not just about following the protocol; it’s about ensuring every detail is implemented correctly.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Use cryptographically secure random number generators for ephemeral keys. Validate all inputs (e.g., A, B, u) to ensure they meet protocol constraints. Clear sensitive data (e.g., passwords, session keys) from memory after use.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cross-Disciplinary Knowledge is Key
&lt;/h3&gt;

&lt;p&gt;Implementing SRP required knowledge of cryptography, software engineering, and network protocols. Understanding the theoretical foundations (e.g., zero-knowledge proofs, modular arithmetic) was just as important as writing the code.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Cryptographic implementations demand a balance of theoretical understanding and practical engineering skills.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Invest time in studying the underlying mathematics and security principles before diving into the implementation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Iterative Development Works Best
&lt;/h3&gt;

&lt;p&gt;The SRP implementation was built iteratively, starting with the registration flow, followed by the authentication flow, and finally the integration of all components.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Tackling one part of the protocol at a time reduces the risk of being overwhelmed and allows for focused testing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Break the implementation into milestones and validate each step before moving to the next.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Standards Are Your Guide
&lt;/h3&gt;

&lt;p&gt;RFC 5054 [1] provided a clear road map for implementing SRP. Adhering to the standard ensured that the implementation was interoperable and secure.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lesson Learned&lt;/strong&gt;: Standards like RFC 5054 [1] are invaluable for ensuring correctness and interoperability.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Best Practice&lt;/strong&gt;: Always refer to the official specification and test against its requirements.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Quick Demo of the SRP protocol
&lt;/h2&gt;

&lt;p&gt;In this section it is shown a quick demo of the SRP protocol, and in the end the unit tests are executed as well. The server process is launched first to ensure that the client's request reach it's destination, &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36/Problem_36_Cryptopals_quick_demo_SRP_protocol.mp4" rel="noopener noreferrer"&gt;video 1: SRP protocol implementation demo in the first part, complete set of unit tests in the last part of the video&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Explore the Code
&lt;/h2&gt;

&lt;p&gt;If you’re interested in diving deeper into the implementation, you can find the full source code, including all tests and Python validation scripts, on my GitHub repository: &lt;a href="https://github.com/Photon-einstein/Cryptopals/tree/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_36" rel="noopener noreferrer"&gt;GitHub Repository - SRP Implementation&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  References:
&lt;/h2&gt;

&lt;p&gt;[1] D. Taylor, T. Wu, N. Mavrogiannopoulos, and T. Perrin, "Using the Secure Remote Password (SRP) Protocol for TLS Authentication," IETF RFC 5054, November 2007. [Online]. Available: &lt;a href="https://datatracker.ietf.org/doc/html/rfc5054" rel="noopener noreferrer"&gt;https://datatracker.ietf.org/doc/html/rfc5054&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;[2] Wikipedia, "Secure Remote Password Protocol," [Online]. Available: &lt;a href="https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>cryptography</category>
      <category>cpp</category>
      <category>srp</category>
    </item>
    <item>
      <title>Man in the Middle Attack to the Diffie Hellman key exchange: g parameter injection variant</title>
      <dc:creator>Tiago Sousa</dc:creator>
      <pubDate>Sat, 02 Aug 2025 11:32:47 +0000</pubDate>
      <link>https://dev.to/tiago_sousa_4baece16501be/man-in-the-middle-attack-to-the-diffie-hellman-key-exchange-g-parameter-injection-variant-4oe6</link>
      <guid>https://dev.to/tiago_sousa_4baece16501be/man-in-the-middle-attack-to-the-diffie-hellman-key-exchange-g-parameter-injection-variant-4oe6</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;The &lt;a href="https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf/?trackingId=9lSn7AbjxtZeHjnllP0TzQ%3D%3D" rel="noopener noreferrer"&gt;Diffie Hellman key exchange protocol&lt;/a&gt; [1] normally have the group values (prime p and generator g) defined statically containing a standardized list of values. In this article I will explain what can happen if those values are negotiated dynamically instead of statically from a few standardized values contained on the RFC 3526 [2].&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are the values negotiated via the RFC 3526 ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;RFC 3526 defines a standardized Modular Exponential Groups (MODP) to be used in the Diffie Hellman (DH) key exchange protocol. These values are public but critical for the security, efficiency and success of this protocol.&lt;/p&gt;

&lt;p&gt;RFC 3526 provides predefined &lt;strong&gt;prime p&lt;/strong&gt; and &lt;strong&gt;generator g&lt;/strong&gt; for DH groups of various sizes, depending on the security requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;1536-bit MODP Group&lt;/strong&gt; (not recommended anymore)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;2048-bit MODP Group&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;3072-bit MODP Group&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;4096-bit MODP Group&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;6144-bit MODP Group&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;8192-bit MODP Group&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each group specifies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;prime p&lt;/strong&gt;: a large safe prime, such that (p-1)/2 is also prime, called a Sophie Germain prime.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;generator g&lt;/strong&gt;: usually g = 2 &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The 1536 bit MODP group is not recommended anymore because as the computational capabilities increased, well funded adversaries can run precompute data used on the DH key exchange protocol for each (p, g) pair using the Number Field Sieve Algorithm (NFS) creating big tables of modular logarithms that can afterwards be used to access large number of websites that use that particular MODP group. This attack was already shown on the Logjam Attack paper (2015) [3].&lt;/p&gt;

&lt;p&gt;Here is an example of a 6144-bit MODP Group present in the RFC 3526 in hexadecimal format:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During the TLS handshake, the first steps in the Diffie Hellman Key exchange protocol is to negotiate the DH group to use (e.g. MODP 2048-bit group), that defines the value of the prime p and the generator g. &lt;/p&gt;

&lt;p&gt;These values are not secret, but are instead public and standardized.&lt;/p&gt;

&lt;p&gt;These two values are important because the strength of the DH depends on the size of the prime p.&lt;/p&gt;

&lt;h3&gt;
  
  
  The use of standardized parameter groups allows or requires:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Security&lt;/strong&gt;: The larger the prime p, the harder the discrete logarithm problem, as the problem space increases with the size of the prime. The RFC 3526 ensures well chosen, trusted primes to prevent backdoors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interoperability&lt;/strong&gt;: predefined groups means all compliant system can interoperate without the necessity to generate new prime numbers every time, that is an expensive operation and error prone as the prime has to meet certain requirements such as to be of the form p = 2q+1 where p is prime. Also p should be generated using a verified random process.&lt;/p&gt;

&lt;p&gt;The generator should also meet security requirements such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the correct sub group should be of the form that g ^ q = 1 mod p&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Mitigating precomputation attacks&lt;/strong&gt;: when a large number of websites uses the same group, attackers can precompute a database of discrete logarithms (Logjam attack) [3] and dilute the attack cost based on the access to that large number of users, so this is a trade-off that has to be taken into consideration, when the computational technology evolves or faster algorithms are published the minimum MODP security requirements should be reviewed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;: large groups guarantee more security but are slower, as the computation will take more time to complete.&lt;/p&gt;

&lt;p&gt;Negotiations on a case by case regarding security requirements allow a better balance of security and efficiency as a security and performance compromise.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What can happen if the prime p and generator g are negotiated dynamically ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If the prime p and generator g are negotiated dynamically instead of statically via the already mentioned MODP Groups present on the RFC 3526, a MitM attack can inject weak or malicious parameters into the real server, breaking intended security of the DH key exchange protocol.&lt;/p&gt;

&lt;p&gt;Here follows some of the malicious parameters that can be injected by a MitM attacker:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Weak prime p&lt;/strong&gt;: if p is too small (e.g. 512 bits), the discrete log problem becomes easy, and the attacker can compute the shared key in real time using the Logjam Attack [3] by means of a precomputed table of discrete logarithms results using the NFS algorithm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Composite or non-prime p&lt;/strong&gt;: if the p is composite the security will depend on the strength of the smaller prime, so the bit security of the p will be much less than intended, and directly proportional to the strength of the smaller prime factor of that composite p. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Generator g set to 1&lt;/strong&gt;, then:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;at Alice side, for a given secret key &lt;strong&gt;a&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;A&lt;/strong&gt; will result in the following: A = g ^ a mod p = 1 ^ a mod p = &lt;strong&gt;1&lt;/strong&gt;. &lt;/li&gt;
&lt;li&gt;at Bob side, for a given secret key &lt;strong&gt;b&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;B&lt;/strong&gt; will result in the following: B = g ^ b mod p = 1 ^ b mod p = &lt;strong&gt;1&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The resulting shared key, will be computed at Alice side by means of: &lt;strong&gt;S&lt;/strong&gt; = B ^ a mod p = 1 ^ a mod p = 1 and on Bob side: S = A ^ b mod p = 1 ^ b mod p = &lt;strong&gt;1&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Generator g set to p&lt;/strong&gt;, then:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;at Alice side, for a given secret key &lt;strong&gt;a&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;A&lt;/strong&gt; will result in the following: A = g ^ a mod p = p ^ a mod p = &lt;strong&gt;0&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;at Bob side, for a given secret key &lt;strong&gt;b&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;B&lt;/strong&gt; will result in the following: B = g ^ b mod p = p ^ b mod p = &lt;strong&gt;0&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The resulting shared key, will be computed at Alice side by means of: &lt;strong&gt;S&lt;/strong&gt; = B ^ a mod p = 0 ^ a mod p = 0 and on Bob side: S = A ^ b mod p = 0 ^ b mod p = &lt;strong&gt;0&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Generator g set to p-1&lt;/strong&gt;, then: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;at Alice side, for a given secret key &lt;strong&gt;a&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;A&lt;/strong&gt; will result in the following: A = g ^ a mod p = (p-1) ^ a mod p = (-1) ^ a mod p = &lt;strong&gt;+/- 1&lt;/strong&gt; , with the signal depending on the parity of value a.&lt;/li&gt;
&lt;li&gt;at Bob side, for a given secret key &lt;strong&gt;b&lt;/strong&gt; the calculation of the resulting public key &lt;strong&gt;B&lt;/strong&gt; will result in the following: B = g ^ b mod p = (p-1) ^ b mod p = (-1) ^ b mod p = &lt;strong&gt;+/- 1&lt;/strong&gt; , with the signal depending on the parity of value b.&lt;/li&gt;
&lt;li&gt;The resulting shared key, will be computed at Alice side by means of: &lt;strong&gt;S&lt;/strong&gt; = B ^ a mod p = (+/-1) ^ a mod p = +/- 1 and on Bob side: S = A ^ b mod p = (+/-1) ^ b mod p = &lt;strong&gt;+/-1&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;The signal of S will depend on the parity of number (ab). This manipulation will reduce the security to 1 bit of entropy. &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  MitM attack to the DH key exchange protocol implementation:
&lt;/h3&gt;

&lt;p&gt;In this section is presented a practical implementation of the MitM attack to the DH key exchange protocol with a g parameter injection variant.&lt;/p&gt;

&lt;p&gt;Mallory in this example is replacing the URL of the real server.&lt;/p&gt;

&lt;p&gt;In a real word scenario the initial communication between the two would need to be downgraded to HTTP and Mallory would need to use a software like Wireshark or mitmproxy to catch the data between the two, change it and send it afterwards to the destiny.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;g&lt;/strong&gt; and &lt;strong&gt;p&lt;/strong&gt; parameters are being exchanged via REST messages, this example exemplifies the importance of adhering to the standard RFC 3526 [2] to avoid the values to be swapped dynamically by a third party in the middle of the communication channel.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_35/uml_diagrams/MITM_with_injected_g_parameters_attack_class_diagram.svg" rel="noopener noreferrer"&gt;class diagram of this solution&lt;/a&gt; is present at figure 1:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsf0ssiu0y5ffnee59cid.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsf0ssiu0y5ffnee59cid.png" alt="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_35/uml_diagrams/MITM_with_injected_g_parameters_attack_class_diagram.svg" width="800" height="673"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The communication between the client and the server is done via HTTP requests and it is the client that has the initiative on this protocol.&lt;/p&gt;

&lt;p&gt;The server exposes three endpoints:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;one to execute the DH key exchange protocol via the &lt;strong&gt;POST /keyExchange&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;one to retrieve all the session keys created on the server side via the &lt;strong&gt;GET /sessionsData&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;one to perform a secure message exchange with a client after the DH key exchange protocol has been completed via the &lt;strong&gt;GET /messageExchange&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_35/uml_diagrams/MITM_with_injected_g_parameters_attack_sequence_diagram.svg" rel="noopener noreferrer"&gt;sequence diagram of this attack&lt;/a&gt; is shown next, figure 2, it is possible to see in detail the actions that the attacker Mallory is performing to the DH key exchange protocol in the initial &lt;strong&gt;POST /keyExchange&lt;/strong&gt; endpoint and afterwards on the &lt;strong&gt;GET/messageExchange&lt;/strong&gt; itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjz6aw4kd48jem7zk9wjk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjz6aw4kd48jem7zk9wjk.png" alt="Sequence diagram of this attack, MitM attack with injection of malicious " width="800" height="917"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Main results obtained during the attack:
&lt;/h3&gt;

&lt;p&gt;The attack was perform for the different possible scenarios, here are the results:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For the substitution of &lt;strong&gt;g = 1&lt;/strong&gt; at the MitM, we got the following result for a given simulation at figure 3:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Funz793pc5u8gs24zo5t6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Funz793pc5u8gs24zo5t6.png" alt="Result of the simulation of the substitution of g = 1 at the MitM attack." width="800" height="141"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see the shared secret at the server is equal to &lt;strong&gt;1&lt;/strong&gt; and then the derived key material will be derive from the nonce's from the client and the server, that are public, so the security is eliminated.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For the substitution of &lt;strong&gt;g = p&lt;/strong&gt; at the MitM, we got the following result for a given simulation at figure 4:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhx84wh1cyiyg7yj3qz4v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhx84wh1cyiyg7yj3qz4v.png" alt="Result of the simulation of the substitution of g = p at the MitM attack." width="800" height="161"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For the substitution of &lt;strong&gt;g = p-1&lt;/strong&gt; at the MitM, we got the two results for a given simulation, the first one is present at figure 6:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6rpjkbwj4qdggdyp8hrj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6rpjkbwj4qdggdyp8hrj.png" alt="Result of the simulation of the substitution of g = p-1 at the MitM attack, case 1, with the result equal to 1." width="800" height="141"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The second result, that is equal to &lt;strong&gt;p-1&lt;/strong&gt; can also appear for the substitution of &lt;strong&gt;g = p-1&lt;/strong&gt;, being the resulting shared secret non deterministic, with the space result of &lt;strong&gt;{-1, 1}&lt;/strong&gt;, figure 7.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiwstxcu276glngf8z21x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiwstxcu276glngf8z21x.png" alt=" Result of the simulation of the substitution of g = p-1 at the MitM attack, case 2, with result equal to p-1." width="800" height="307"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next follows a quick demo of this attack, video 1, with the client on the left screen, Mallory's fake server in the middle screen and the real server on the right. The client will try to perform the POST /keyExchange first, and as it succeeds, it will latter also perform the GET /messageExchange message, both communications will pass the client verification's, so he remains oblivious of the actions of Mallory the whole time.&lt;/p&gt;

&lt;p&gt;All the requests from the client are relayed by the fake Mallory server to the real server, in spite of that, there is no error being triggered by the real server.&lt;/p&gt;

&lt;p&gt;This demo is for the injection of the malicious parameter of &lt;strong&gt;g = 1&lt;/strong&gt; by the MitM. The resulting shared secret key on the server on the right is possible to observe, being equal to &lt;strong&gt;1&lt;/strong&gt; as expected.&lt;/p&gt;

&lt;p&gt;MitM attack with malicious g parameter injection g = 1 is present at the following link: &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_35/Problem_35_Cryptopals_quick_demo_g_equals_1.mp4" rel="noopener noreferrer"&gt;demo&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to protect against a MitM attack against the DH key exchange protocol
&lt;/h3&gt;

&lt;p&gt;The MitM attack exposes a critical vulnerability in the original Diffie Hellman key exchange, namely the lack of &lt;strong&gt;authentication&lt;/strong&gt;. While DH key exchange protocol was able to solve very cleverly the problem of establishing a shared secret over an insecure channel, it doesn't verify the identities of the parties involved.&lt;/p&gt;

&lt;p&gt;To secure Diffie Hellman against MitM attacks, the messages exchanged between Alice and Bob, namely their public keys A and B, must be authenticated. This ensures that the public keys received truly belong to Alice and Bob, preventing Mallory from replacing her own keys [4].&lt;/p&gt;

&lt;p&gt;In the case of the current attack in specific, it is also recommended to not publicly exchange and negotiate the p and g parameters but instead exchange the Diffie Hellman Groups for the Internet Key Exchange present on the RFC 3526 statically via their group identification.&lt;/p&gt;

&lt;h3&gt;
  
  
  References:
&lt;/h3&gt;

&lt;p&gt;[1] T. Sousa, "Diffie-Hellman Key Exchange Protocol," LinkedIn, June 2025. [Online]. Available: &lt;a href="https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf" rel="noopener noreferrer"&gt;https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;[2] D. Kivinen and H. Krawczyk, "More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)," IETF RFC 3526, May 2003. [Online]. Available: &lt;a href="https://datatracker.ietf.org/doc/html/rfc3526" rel="noopener noreferrer"&gt;https://datatracker.ietf.org/doc/html/rfc3526&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;[3] D. Adrian et al., "Imperfect Forward Secrecy: How Diffie-Hellman Fails in Practice," in Proceedings of the 22nd ACM Conference on Computer and Communications Security (CCS), Oct. 2015. [Online]. Available: &lt;a href="https://weakdh.org/imperfect-forward-secrecy.pdf" rel="noopener noreferrer"&gt;https://weakdh.org/imperfect-forward-secrecy.pdf&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;[4] T. Sousa, "Man-in-the-Middle Attack in Diffie-Hellman Key Exchange Protocol," LinkedIn, July 2025. [Online]. Available: &lt;a href="https://www.linkedin.com/pulse/man-middle-attack-diffie-hellman-key-exchange-protocol-tiago-sousa-7fdhf" rel="noopener noreferrer"&gt;https://www.linkedin.com/pulse/man-middle-attack-diffie-hellman-key-exchange-protocol-tiago-sousa-7fdhf&lt;/a&gt;.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>SVG's images advantages and use cases</title>
      <dc:creator>Tiago Sousa</dc:creator>
      <pubDate>Fri, 11 Jul 2025 14:04:12 +0000</pubDate>
      <link>https://dev.to/tiago_sousa_4baece16501be/svgs-images-advantages-and-use-cases-5f2j</link>
      <guid>https://dev.to/tiago_sousa_4baece16501be/svgs-images-advantages-and-use-cases-5f2j</guid>
      <description>&lt;p&gt;𝗦𝗩𝗚 (Scalable Vector Graphics) is an XML based vector image format for two-dimensional graphics.&lt;/p&gt;

&lt;p&gt;Main characteristics of SVG files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;XML based: Unlike the binary image formats (e.g. PNG, JPEG or GIF) an SVG file is only a text file written in XML (eXtensible Markup Language). This means that it's file can be opened on a text editor and its content read. It can contain tags such as circle, rect, path or text, each with attributes that can define position, size, color and other properties.&lt;br&gt;
This is an advantage for developers because being XML based make these files programmable and version controllable instead of static binary files such as PNP and JPEG formats.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Vector Graphics: SVG images are composed of vector graphics, this makes the difference from "raster graphics" used at PNG's and JPEG's image format.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Raster Images: The images of this kind such as PNG and JPEG are composed with a grid of individual pixels, when a zoom is done in a raster image, the individual pixels start to show up, leading to a blurry appearance and low resolution resulting in a low quality image.&lt;/p&gt;

&lt;p&gt;Vector Images (SVG): These images of this kind, such as SVG are defined by mathematical equations and geometric objects such as points, lines, curves and shapes. With this type of image, instead of being stored pixel data, an SVG file stores instead how to draw the image.&lt;br&gt;
This allows an unmatched scalability, allowing the images to be rendered perfectly at any size or resolution without any loss of quality.&lt;/p&gt;

&lt;p&gt;Cons of SVG:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Not ideal for complex photographs: while it would also be possible to use SVG in complex photos, every pixel would need complex mathematical description, and the file's size would be very large.&lt;/li&gt;
&lt;li&gt;Increased complexity for creation: as the complexity of the images increase the technical knowledge requirements of vector graphics software will also increase.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Best use cases in Software context for SVG image format:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Logos and icons;&lt;/li&gt;
&lt;li&gt;User interface elements such as buttons, form controls and others;&lt;/li&gt;
&lt;li&gt;Diagrams and flowcharts (Class, Sequence, Architecture): where scalability, traceability, edibility and programmatic generation are important;&lt;/li&gt;
&lt;li&gt;Data visualizations: Interactive charts, graphs and maps;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On figure 1 is possible to see the advantage of svg images compared to a png, when there is the need to have a high resolution.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn3hrqppq6l2pva1q1gha.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn3hrqppq6l2pva1q1gha.png" alt="Figure 1: Side by side comparison between a png and a svg image" width="800" height="747"&gt;&lt;/a&gt;&lt;br&gt;
Figure 1: Side by side comparison between a png and a svg image&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In conclusion&lt;/strong&gt;: &lt;br&gt;
SVG can be a good format if you want to work with an Icon, logo, diagram or interactive graphics, where scalability, editability, programmatic control, resolution independence and traceability are important.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Man in the middle attack in the Diffie Hellman key exchange protocol and how to defend against it</title>
      <dc:creator>Tiago Sousa</dc:creator>
      <pubDate>Thu, 10 Jul 2025 12:54:35 +0000</pubDate>
      <link>https://dev.to/tiago_sousa_4baece16501be/man-in-the-middle-attack-in-the-diffie-hellman-key-exchange-protocol-and-how-to-counter-it-1hjj</link>
      <guid>https://dev.to/tiago_sousa_4baece16501be/man-in-the-middle-attack-in-the-diffie-hellman-key-exchange-protocol-and-how-to-counter-it-1hjj</guid>
      <description>&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;After having explained on the previous article what is the &lt;a href="https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf/?trackingId=9lSn7AbjxtZeHjnllP0TzQ%3D%3D" rel="noopener noreferrer"&gt;Diffie Hellman key exchange protocol&lt;/a&gt;, in this present article I will talk about a possible attack that this protocol can suffer if no authentication of any party involved is performed.&lt;/p&gt;

&lt;p&gt;The article will touch upon the following topics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;what is and how it works the man in the middle attack in the context of the Diffie Hellman key exchange protocol;&lt;/li&gt;
&lt;li&gt;what is and how it works the parameter injection in the context of the Diffie Hellman key exchange protocol;&lt;/li&gt;
&lt;li&gt;what was the structure used in this prove of concept, and the results obtained;&lt;/li&gt;
&lt;li&gt;a quick demo of the attack taken place;&lt;/li&gt;
&lt;li&gt;a mitigation action to prevent this attack and why it works;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Man in the Middle Attack (MitM) explained
&lt;/h2&gt;

&lt;p&gt;The Diffie Hellman key exchange protocol addresses the fundamental necessity of two independent parties to agree upon a secret key without any prior shared secret, even if their entire conversation is openly observed by an adversary. &lt;/p&gt;

&lt;p&gt;The basic Diffie Hellman key exchange protocol, on its pure form, possesses a critical vulnerability, as it provides no inherent authentication of the parties involved. &lt;/p&gt;

&lt;p&gt;This opens the door to a MitM attack, in such an attack, a malicious third party, often named Mallory, places itself between Alice and Bob, intercepting, passing or even altering their communications, all while each party believe they are communicating directly with each other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Diffie Hellman (DH) key exchange quick recap
&lt;/h2&gt;

&lt;p&gt;At its core, the DH key exchange protocol relies on the mathematical properties of the modular exponentiation and the computational difficulty of the Discrete Logarithm Problem (DLP), the main steps are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Public agreed parameters&lt;/strong&gt;: Alice and Bod first openly agreed on  two large numbers, that are standardize [2].    &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A large prime number, p. &lt;/li&gt;
&lt;li&gt;A generator g (a number whose powers modulo p generate a large set of number between [0, p-1] if p is a big prime number.
These parameters are public and known to anyone, including the eavesdropper.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Private key generation&lt;/strong&gt;: each party in this protocol uses a cryptographic secure pseudo random number generator (CSPRNG) to avoid predictability to choose a private key.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice secretly chooses a large random integer number, her private key a such that
1&amp;lt;a&amp;lt;p-1.&lt;/li&gt;
&lt;li&gt;Bob secretly chooses a large random integer number, her private key b such that
1&amp;lt;b&amp;lt;p-1.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Public key generation&lt;/strong&gt;: each party in this protocol performs the following calculation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice computes her public key: A = g&lt;sup&gt;a&lt;/sup&gt; (mod p)&lt;/li&gt;
&lt;li&gt;Bob computes his public key: B = g&lt;sup&gt;b&lt;/sup&gt; (mod p)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The exchange of public keys:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice sends her public key A to Bob.&lt;/li&gt;
&lt;li&gt;Bob send his public key B to Alice.
Even if a eavesdropper observes A, B, g and p, it is computationally infeasible for him to derive a and b due to the DLP difficulty.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Shared secret calculation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice computes the shared secret:  K = B&lt;sup&gt;a&lt;/sup&gt; (mod p)&lt;/li&gt;
&lt;li&gt;Bob computes the shared secret: K = A&lt;sup&gt;b&lt;/sup&gt; (mod p)
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;They both arrive at the same exact shared secret K since:&lt;br&gt;
B&lt;sup&gt;a&lt;/sup&gt; (mod p) = (g&lt;sup&gt;b&lt;/sup&gt;)&lt;sup&gt;a&lt;/sup&gt; (mod p) = g&lt;sup&gt;ba&lt;/sup&gt; (mod p) = K&lt;br&gt;
A&lt;sup&gt;b&lt;/sup&gt; (mod p) = (g&lt;sup&gt;a&lt;/sup&gt;)&lt;sup&gt;b&lt;/sup&gt; (mod p) = g&lt;sup&gt;ab&lt;/sup&gt; (mod p) = K&lt;/p&gt;

&lt;p&gt;The virtue of the DH key exchange protocol is that it provides the ability to establish a shared secret without never transmitting the secret itself. However, its main flaws is that it does not provide any mechanism for Alice to verify that she is truly exchanging keys with Bob, and on the same manner, that Bob is really exchanging keys with Alice, this is the reason why the MitM attack is possible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Possible scenarios where the MitM attack can be executed
&lt;/h2&gt;

&lt;p&gt;There are several practical scenarios where the MitM attack can be executed, here are some of them:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Public Wi-Fi  eavesdropping&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scenario: A person connects to a free, open Wi-Fi newtwork in a public space.&lt;/li&gt;
&lt;li&gt;Attack: The attacker uses a  rogue hotspot (e.g. "Free_Airport_WiFi") or is connected to the same network and uses packet sniffing tools (e.g. Wireshark or mitmproxy) to intercept unencrypted traffic.&lt;/li&gt;
&lt;li&gt;Result: If that person is visiting an unencrypted (non HTTPS) website, the attacker sees their persons credentials or session data.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;SSL stripping&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scenario: A person is visiting a website that should be secure (HTTPS), but an attacker downgrades the connection to HTTP.&lt;/li&gt;
&lt;li&gt;Attack: The attacker intercepts the initial connection and removes the HTTPS encryption, forcing the user to use plain HTTP instead.&lt;/li&gt;
&lt;li&gt;Result: The attacker sees everything in plaintext.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;ARP Spoofing (Local Network MitM)&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scenario: A person is on the same local network as the attacker.&lt;/li&gt;
&lt;li&gt;Attack: The attacker sends fake ARP messages to associate their MAC address with the IP address of the gateway.&lt;/li&gt;
&lt;li&gt;Result: All the traffic of that user goes through the attacker's machine before reaching the service destination on the internet.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Compromised Router or internet service provider (ISP)&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scenario: A home router is misconfigured or compromised.&lt;/li&gt;
&lt;li&gt;Attack: The attacker intercepts and alters the DNS queries or the HTTP traffic at the router level.&lt;/li&gt;
&lt;li&gt;Result: Redirected sites, credential theft or malware injection.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;MitM in cryptography protocols (e.g.: Diffie Hellman key exchange protocol)&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scenario: Alice and Bob are performing a key exchange protocol.&lt;/li&gt;
&lt;li&gt;Attack: The attacker intercepts the key exchange and establishes two independently and separated keys with Alice and Bob.&lt;/li&gt;
&lt;li&gt;Result: The attacker can read, modify and relay all encrypted messages between Alice and Bob.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  MitM attack in Diffie Hellman key exchange protocol explained
&lt;/h2&gt;

&lt;p&gt;The crucial part of this attack is that the attacker, Mallory, is able to set up two independent keys with Alice and Bob, here is a sequential walk through of the attack:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Alice initiates the Key Exchange&lt;/strong&gt;: Alice generates her private key a and computes her public key A = g&lt;sup&gt;a&lt;/sup&gt; (mod p). She sends p, g and A to Bob.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory intercepts Alice's public key&lt;/strong&gt;: Mallory intercepts Alice's message containing p, g and A to Bob.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory impersonates Alice to Bob&lt;/strong&gt;: Instead of forwarding Alice's actual public key to Bob, Mallory generates his own private key, let's consider mA. He then computes his own public key MA =g&lt;sup&gt;mA&lt;/sup&gt; (mod p). Afterwards, Mallory sends p, g and MA to Bob, instead of the actual Alice's public key A.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bob responds to Mallory (thinking it is Alice)&lt;/strong&gt;: Bob receives MA (thinking it is A instead). He generates his private key b, computes his public key B = g&lt;sup&gt;b&lt;/sup&gt;(mod p), and calculates a shared secret with Mallory public key, instead of Alice's:&lt;br&gt;&lt;br&gt;
Kbm = (MA)&lt;sup&gt;b&lt;/sup&gt;(mod p). Bob then sends his public key B back to Alice, unaware that is Mallory that is receiving it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory intercepts Bob's public key&lt;/strong&gt;: Mallory intercepts Bob's message containing B.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory impersonates Bob to Alice&lt;/strong&gt;: Instead of forwarding Bob's actual public key B to Alice, Mallory generates another private key, mB. He computes his own public key MB = g&lt;sup&gt;mB&lt;/sup&gt;(mod p). Mallory them sends  MB to Alice, pretending that MB is Bob's public key.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Alice completes the key exchange with Mallory (thinking it's Bob)&lt;/strong&gt;: Alice receives MB (thinking it is B). She then calculates a shared secret with Mallory instead of Bob:                 Kam = (MB)&lt;sup&gt;a&lt;/sup&gt; (mod p).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the end of this exchange, Mallory is in the possession of two separate shared secrets, such that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice believes she has established a shared secret Kam with Bob.&lt;/li&gt;
&lt;li&gt;Bob believes he has established a shared secret Kbm with Alice.&lt;/li&gt;
&lt;li&gt;Mallory knows both Kam and Kbm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As Kam and Kbm are entirely different secrets, both Alice and Bob are communicating securely with Mallory instead with each other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Attack in action
&lt;/h2&gt;

&lt;p&gt;After Mallory has setup two distinct shared secrets with both Alice and Bob, he can now act as a transparent proxy, in the following manner:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Alice to Bob: When Alice encrypts a message using Kam and sends it to Bob, Mallory intercepts it and decrypts it using Kam also, reads the plaintext, and latter modifies or just pass the original message, encrypting it again now with Kbm before sending it to Bob. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Bob to Alice: When Bob encrypts a message using his symmetric key Kbm and then sends it to Alice, Mallory can intercept it and decrypt it, using Kbm. He can then read and/or potentially modify and afterwards re-encrypt it again using this time the Kam before sending it to Alice. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;From both Alice and Bob's perspective, their communications seems secure and private, they have no clue that their messages are being read or potentially altered by a third party. &lt;/p&gt;

&lt;p&gt;This complete failure on confidentiality and integrity is the consequence of MitM attack when there is no &lt;strong&gt;authentication&lt;/strong&gt; on the Diffie Hellman key exchange protocol.&lt;/p&gt;

&lt;h2&gt;
  
  
  MitM attack with parameter injection with prime p
&lt;/h2&gt;

&lt;p&gt;One variant of the MitM attack is the parameter injection, in this example with the prime p as the parameter injected. This attack forces the shared secret between the two parties to become a known and trivial value as I will try to show next.&lt;/p&gt;

&lt;p&gt;This result is achieved by means of the properties of the modular arithmetic to fix the shared secret between Alice and Bob to &lt;strong&gt;zero&lt;/strong&gt; o by injecting the prime p itself, here follows the steps with Mallory's injection strategy:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Alice initiates the Key Exchange&lt;/strong&gt;: Alice generates her private key a and computes her public key A = g&lt;sup&gt;a&lt;/sup&gt; (mod p). She sends p, g and A to Bob.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory intercepts Alice's public key (A)&lt;/strong&gt;: Mallory intercepts A. Instead of him generating his own public key he performs the substitution in the next step.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory injects p to Bob&lt;/strong&gt;: Mallory sends the large prime p instead of his public key, pretending it is Alice's public key, MA = p. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bob's shared secret calculation&lt;/strong&gt;: Bob receives MA = p (thinking it is Alice's A). He then computes his shared secret Kbm using this private key b.&lt;br&gt;&lt;br&gt;
                                                       Kbm = (MA)&lt;sup&gt;p&lt;/sup&gt; (mod p)  &amp;lt;=&amp;gt; Kbm = p&lt;sup&gt;p&lt;/sup&gt; (mod p) &amp;lt;=&amp;gt; Kbm = 0                                                         because any positive integer power of p will always be a multiple of p.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bob's public key calculation&lt;/strong&gt;: Bob computes his public key B = g&lt;sup&gt;b&lt;/sup&gt; (mod p) and sends it towards Alice.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory intercepts Bob's public key (B)&lt;/strong&gt;: Mallory intercepts B and then performs the same substitution for p instead.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mallory injects p to Alice&lt;/strong&gt;: Mallory sends the large prime number p itself to Alice, pretending it is Bob's public key, so Alice receives MB = p.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Alice's shared secret calculation&lt;/strong&gt;: Alice receives MB = p (thinking it is Bob's B). She then computes his shared secret Kam using this private key a.&lt;br&gt;&lt;br&gt;
                                                  Kam = (MB)&lt;sup&gt;p&lt;/sup&gt; (mod p) &amp;lt;=&amp;gt; Kam = p&lt;sup&gt;p&lt;/sup&gt; (mod p) &amp;lt;=&amp;gt; Kam = 0 because any positive integer power of p will always be a multiple of p.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;At the end of this MitM attack variant, both Alice and Bob believe they have successfully established a shared secret, however, unknown to them, that shared secret is zero, so Mallory can do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Trivial key derivation&lt;/strong&gt;: If Alice and Bob then proceed to derived a symmetric encryption key (e.g. AES) hashing they shared secret (e.g. SHA-256(sharedSecret), they will both compute SHA-256(0) )&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mallory's advantage&lt;/strong&gt;: Since Mallory also knows the shared secret 0, he can also independently compute the exact same SHA-256(0) symmetric key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complete compromise&lt;/strong&gt;: Any further communication encrypted by Alice and Bob's using this derived key can be trivially decrypted so he then can read and potentially also modify and encrypt again the message. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This complete failure on confidentiality and integrity in this variant of the MitM attack is also the effect of having &lt;strong&gt;no authentication&lt;/strong&gt; on the Diffie Hellman key exchange protocol.&lt;/p&gt;

&lt;h2&gt;
  
  
  MitM attack to the DH key exchange protocol implementation:
&lt;/h2&gt;

&lt;p&gt;In this section is is presented a practical implementation of the MitM attack to the DH key exchange protocol, in this example the public parameters p and g are picked from the MODP groups present in the &lt;a href="https://datatracker.ietf.org/doc/html/rfc3526" rel="noopener noreferrer"&gt;RFC3526&lt;/a&gt; [2], each party also generates a nonce for each session created.&lt;/p&gt;

&lt;p&gt;Mallory in this example is replacing the URL of the real server. &lt;/p&gt;

&lt;p&gt;In a real word scenario the initial communication between the two would need to be downgraded to HTTP and Mallory would need to use a software like Wireshark or mitmproxy to catch the data between the two, change it and send it afterwards to the destiny.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_34/uml_diagrams/MITM_attack_class_diagram.svg" rel="noopener noreferrer"&gt;class diagram of this solution&lt;/a&gt;&lt;/strong&gt; is present at figure 1:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzykck70ngsa0wjpcmsnc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzykck70ngsa0wjpcmsnc.png" alt="Figure 1: Class diagram of the MitM attack on the DH key exchange protocol." width="800" height="654"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The communication between the client and the server is done via HTTP requests and it is the client that has the initiative on this protocol.&lt;/p&gt;

&lt;p&gt;The server exposes three endpoints:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;one to execute the DH key exchange protocol via the &lt;strong&gt;POST /keyExchange&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;one to retrieve all the session keys created on the server side via the &lt;strong&gt;GET /sessionsData&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;one to perform a secure message exchange with a client after the DH key exchange protocol has been completed via the &lt;strong&gt;GET /messageExchange&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_34/uml_diagrams/MITM_attack_sequence_diagram.svg" rel="noopener noreferrer"&gt;sequence diagram of this attack&lt;/a&gt; is shown next, figure 2, it is possible to see in detail the actions that the attacker Mallory is performing to the DH key exchange protocol in the initial &lt;strong&gt;POST /keyExchange&lt;/strong&gt; endpoint and afterwards on the &lt;strong&gt;GET/messageExchange&lt;/strong&gt; itself (full diagram in .svg format in the link above).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzuy2ird6do9ist5a78c1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzuy2ird6do9ist5a78c1.png" alt="Sequence diagram of the MitM attack on the DH key exchange protocol." width="800" height="922"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next follows a quick demo of this attack, video 1, with the client on the left screen, Mallory's fake server in the middle screen and real server on the right. The client will try to perform the POST /keyExchange first, and as it succeeds, it will latter also perform the GET /messageExchange message, both communications will pass the client verification's, so he remains oblivious of the actions of Mallory the whole time. &lt;/p&gt;

&lt;p&gt;All the requests from the client are relayed by the fake Mallory server to the real server, in spite of that, there is no error being triggered by the real server as is possible to see on this &lt;a href="https://github.com/Photon-einstein/Cryptopals/blob/main/Cryptopals_resolutions/5-Set_5/cryptopals_set_5_problem_34/demo_MITM_attack_on_DH_key_exchange_protocol.mp4" rel="noopener noreferrer"&gt;demo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In figure 3 it is possible to observe the output of the GET /sessionsData after the client has done the requests, both the Mallory's fake server and the real server have the same session id and client id on their databases but the other session's data such as nonce's and derived symmetric key's are different as the communication's channel session data are entirely different between those two sessions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw7wy67dqpq9jbxt9twui.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw7wy67dqpq9jbxt9twui.png" alt="Figure 3: MitM attack's output, in terms of session data created on the Mallory's fake server on the left and the real server on the right." width="800" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to protect against a MitM attack against the DH key exchange protocol
&lt;/h2&gt;

&lt;p&gt;The MitM attack exposes a critical vulnerability in the original Diffie Hellman key exchange, namely the lack of &lt;strong&gt;authentication&lt;/strong&gt;. While DH key exchange protocol was able to solve very cleverly the problem of establishing a shared secret over an insecure channel, it doesn't verify the identities of the parties involved.&lt;/p&gt;

&lt;p&gt;To secure Diffie Hellman against MitM attacks, the messages exchanged between Alice and Bob, namely their public keys A and B, must be authenticated. This ensures that the public keys received truly belong to Alice and Bob, preventing Mallory from replacing her own keys.&lt;/p&gt;

&lt;p&gt;The most common and effective way to authenticate public keys in a Diffie Hellman key exchange is through the use of digital signatures, often supported by a Public Key Infrastructure (PKI) and  X.509 certificates. &lt;/p&gt;

&lt;p&gt;X.509 certificates can contain the following main information:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;public key associated with the entity that is trying to authenticate, Alice or Bob in this case.&lt;/li&gt;
&lt;li&gt;Details about the entity, namely a domain name for a website or a user's name for a person.&lt;/li&gt;
&lt;li&gt;Serial number: an unique identifier to identify the certificate.&lt;/li&gt;
&lt;li&gt;Signature Algorithm: Indicates the cryptographic algorithm used to sign the certificate.&lt;/li&gt;
&lt;li&gt;Validity period: defines the start and end dates during witch the certificate is considered valid.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With this update in the protocol, here is the how the DH key exchange would look like:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Introduction to a Trusted &lt;strong&gt;Certificate Authority (CA)&lt;/strong&gt;: Before the communication starts, Alice and Bob obtain a digital certificate from the CA, this certificate binds the public key to an identity (e.g. a domain name or a person). The CA digitally sign this certificate, ensuring the identity's ownership of the public key.&lt;/p&gt;

&lt;p&gt;Built of the certificate:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Subject's info&lt;/li&gt;
&lt;li&gt;Subject's public key
&lt;/li&gt;
&lt;li&gt;Validity dates
&lt;/li&gt;
&lt;li&gt;Extensions info
&lt;/li&gt;
&lt;li&gt;Issuer info&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hashes the to be signed data (TBS)&lt;br&gt;
Example: digest = SHA-256(TBS_data)   &lt;/p&gt;

&lt;p&gt;Signs the hash using the CA private key:&lt;br&gt;
Signature = EncryptCA(digest, privateKeyCA)                                                                                                     &lt;/p&gt;

&lt;p&gt;Attaches the signature to the certificate: &lt;br&gt;
the full certificate X.509 now has the following fields:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To be signed data
&lt;/li&gt;
&lt;li&gt;Signature algorithm (e.g.: SHA-256)&lt;/li&gt;
&lt;li&gt;Signature&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Alice and Bob exchange certificates and their DH public keys:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When Alice initiates the connection, she sends her Diffie Hellman public key                       (A = g&lt;sup&gt;a&lt;/sup&gt; (mod p)) along with her digital certificate.&lt;/li&gt;
&lt;li&gt;When Bob responds, he sends his Diffie Hellman public key (B = g&lt;sup&gt;b&lt;/sup&gt; (mod p)) along with his digital certificate.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Verification of identities and public keys:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Receives the certificate (e.g. during TLS handshake) with the information about the other party involved.&lt;/li&gt;
&lt;li&gt;Extracts from the certificate the signature and the to be signed data.&lt;/li&gt;
&lt;li&gt;Recomputes the hash with the public key received with the signature algorithm, as an example:  &lt;strong&gt;digest&lt;/strong&gt; = SHA-256(to_be_signed_data)&lt;/li&gt;
&lt;li&gt;Decrypts de received signature using the CA's public key: &lt;strong&gt;decryptedDigest&lt;/strong&gt; = decryptCA(signature, publicKeyCA)&lt;/li&gt;
&lt;li&gt;Compares the two digests:
if digest == decryptedDigest:
    -&amp;gt; Certificate is valid and authentic, the public key is verified 
else:
    -&amp;gt; Certificate is invalid or tampered &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This works because only the CA knows its private key, so only CA could have produced a valid signature. In the same manner, anyone with the CA's public key can verify that the certificate hasn't been forged and/or altered by some attacker.&lt;/p&gt;

&lt;p&gt;In a real world scenario, such as TLS (HTTPS) the server sends the certificate to the client's browser, the client's browser then verifies the validity of the certificate received using for that matter the trusted CA root public key. [3]&lt;/p&gt;

&lt;p&gt;If the certificate is verified, the client's browser trust the server's identity and public key, allowing the Diffie Hellman secure key exchange to proceed - &lt;strong&gt;Diffie Hellman with authentication&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  References:
&lt;/h1&gt;

&lt;p&gt;[1] Sousa, T. (2024, April 23). Diffie-Hellman Key Exchange Protocol. Available at LinkedIn: &lt;a href="https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf" rel="noopener noreferrer"&gt;https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] D. Kivinen and H. Krawczyk, "More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)," IETF RFC 3526, May 2003. Available at: &lt;a href="https://datatracker.ietf.org/doc/html/rfc3526" rel="noopener noreferrer"&gt;https://datatracker.ietf.org/doc/html/rfc3526&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;[3] Rescorla, E. The Transport Layer Security (TLS) Protocol Version 1.3, RFC 8446, IETF, August 2018. Available at: &lt;a href="https://datatracker.ietf.org/doc/html/rfc8446" rel="noopener noreferrer"&gt;https://datatracker.ietf.org/doc/html/rfc8446&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
