Skip to main content

Handshake Flow

LightweightSecureTCP performs a custom three-step handshake to establish a mutually authenticated and encrypted session.
Unlike plain TCP, this ensures that both parties know the shared key and are authorized to proceed.


πŸ” Why Handshake is Necessary​

TCP alone does not provide authentication or encryption.
The handshake in LightweightSecureTCP addresses this by:

  • Verifying that both client and server possess the same 256-bit handshake key
  • Preventing unauthorized devices from connecting
  • Generating a temporary session key unique to each connection

If the handshake fails, the connection is closed immediately and no session is created.


πŸ“¦ Handshake Packet Sequence​

  1. Client β†’ Server Sends HandshakeRequest containing:

    • A 32-bit random nonce
    • Two 64-bit random numbers (The payload is encrypted using the static key)
  2. Server β†’ Client Sends HandshakeResponse containing:

    • The encrypted sum and XOR of the received numbers (verifies client’s data)
    • A new 32-bit challenge nonce for the client (Payload is encrypted using the static key)
  3. Client β†’ Server Sends HandshakeSuccess containing:

    • A newly generated session key (for future communication)
    • Encrypted using the static key

βœ… If all validations pass, the handshake is complete and the session is securely established.


πŸ”„ After a Successful Handshake​

  • Client gains access to the communication channel
  • Server creates a Session object and calls onHandshakeSuccess(...)
  • A new session key is generated by the server after the successful handshake
  • Messages are encrypted using this session key

❌ What Happens on Failure?​

If any step fails (invalid encryption, wrong key, timeout, malformed packet):

  • The handshake is immediately aborted
  • The socket is closed
  • The callback onHandshakeFailed(...) is triggered on both client and server

No session is created, and no data is exchanged.


βœ… Summary​

  • All connections must complete this three-step handshake before any messaging
  • This process ensures mutual trust, key validation, and unique per-session encryption
  • Requires calling:
LightweightSecureTCP::setHandshakeKey(handshakeKey);

on both devices before starting client or server


Ready to learn how each of these 3 packets work? β†’ Check out: LightweightSecureTCP Packets