Search code examples
c#c++windowsdiffie-hellmanpublic-key-exchange

Diffie Hellman key exchange between C# and C++ on Windows


I want to use the Diffie Hellman algorithm to securely exchange keys between a C++ server an a C# client which both are running on Windows. I tried using ECDiffieHellmanCng in C# to generate a public key as follows:

ECDiffieHellmanCng diffieHellman = new ECDiffieHellmanCng
{
    KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
    HashAlgorithm = CngAlgorithm.Sha256
};

byte[] publicKey = diffieHellman.PublicKey.ToByteArray(); // 140 bytes

Furthermore, I'm deriving the AES key using the following code:

var cngKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
var aesKey = diffieHellman.DeriveKeyMaterial(cngKey); // 32 bytes

This works well in a C# context, however I need it to interact with C++.

Is there any C++ library or code which is compatible with ECDiffieHellmanCng? I looked into Crypto++ but it wants me to generate a p, q, and g as well as the public key size being 128 bytes which looks like it's not compatible with my C# key exchange method.

Any other suggestions or code examples for performing the key exchange are welcome regardless.


Solution

  • Since I simply wanted an encrypted connection, going with OpenSSL was the way to go.