NTDLS.SecureKeyExchange Usage
Generating single or multi-round Diffie-Hellman shared secrets in C# with three token exchanges.
NTDLS.SecureKeyExchange
What it is. A small C# library that performs Diffie-Hellman key negotiation out of the box - single round or multi-round. Two peers exchange a couple of byte arrays over any channel (which may itself be public) and end up with an identical shared secret, without ever transmitting the secret itself.
When to reach for it. You are building a custom protocol and need the two ends to agree on an encryption key before switching the connection to encrypted traffic - think pairing a client with a service, or bootstrapping AES keys between your own components. Skip it if you can use TLS; a vetted transport handshake solves this problem with far less surface area to get wrong.
Getting started
The dance is three calls. The initiator generates a negotiation token (the size argument is multiplied by 16 to get the key length), the peer applies it and returns a reply, and the initiator applies the reply:
// localHost starts the process, requesting an 8 * 16 = 128 byte key.
var localHost = new CompoundNegotiator();
byte[] negotiationToken = localHost.GenerateNegotiationToken(8);
// localHost passes the token to the remote peer, which applies it.
var remotePeer = new CompoundNegotiator();
byte[] negotiationReply = remotePeer.ApplyNegotiationToken(negotiationToken);
// The reply travels back, and localHost applies it.
localHost.ApplyNegotiationResponseToken(negotiationReply);
// Both sides now hold the same SharedSecret - verify via the hash.
if (remotePeer.SharedSecretHash != localHost.SharedSecretHash)
{
throw new Exception("This should never happen.");
}
Console.WriteLine($"Key length: {localHost.KeyLength} bytes.");
After the final call, each side reads its key from SharedSecret and can feed it into an AES provider (for example, as the pre-flight step shown in NTDLS.ReliableMessaging's encryption docs). Multi-round negotiation uses the same three-call pattern repeated across rounds.
NuGet: NTDLS.SecureKeyExchange