Blog | G5 Cyber Security

Secure Peer Connection: MitM Protection

TL;DR

Yes, a secure channel can be established between two strangers without a man-in-the-middle (MitM) attack using the Diffie-Hellman key exchange combined with authentication. This guide explains how to do it practically.

Establishing a Secure Channel

  1. Key Exchange Protocol: Diffie-Hellman
  • Generate Key Pairs (Both Peers)
  • Each peer needs to independently generate a private key and corresponding public key.

    openssl genrsa -out peer1_private.pem 2048
    openssl rsa -in peer1_private.pem -pubout -out peer1_public.pem

    (Repeat for Peer 2)

  • Exchange Public Keys
  • Peers exchange their public keys over the insecure channel. This is safe because only the public key is shared.

  • Calculate Shared Secret (Both Peers)
  • Each peer uses their private key and the *other* peer’s public key to calculate a shared secret.

    openssl pkeyutl -derive -pkey peer1_private.pem -inkey peer2_public.pem -out peer1_shared_secret

    (Repeat for Peer 2, swapping keys)

  • Authentication: Digital Signatures
  • Diffie-Hellman alone doesn’t prevent a MitM from impersonating one of the peers. We need authentication.

  • Sign Public Key (Peer 1)
  • openssl dgst -sha256 -sign peer1_private.pem -out peer1_public.sig peer1_public.pem
  • Verify Signature (Peer 2)
  • openssl dgst -sha256 -verify peer1_public.pem -signature peer1_public.sig

    (Repeat for Peer 2, swapping keys)

  • Symmetric Encryption: Using the Shared Secret
  • Once authenticated, use the shared secret to generate a symmetric encryption key (e.g., using KDF – Key Derivation Function).

    openssl kdf -pbkdf2 -digest sha256 -salt  -iter 10000 peer1_shared_secret -out symmetric_key

    Use the symmetric key to encrypt all further communication (e.g., with AES).

  • Protecting Against Replay Attacks
  • Important Considerations

    Exit mobile version