Gerald
Gerald

Reputation: 23479

1024-bit Diffie-Hellman in C#

So I'm working on a project to interface a C# client with an existing server technology. One of the requirements is a key exchange using Diffie-Hellman.

We have known public P and G and I need to generate a 1024-bit public key to send to the server.

The following is used on the server side in C++ with OpenSSL. Currently I am using the same code in a native DLL called via P/Invoke, and it works as well. I would prefer to eliminate the native DLL dependency if possible.

char publicKey[128];
char P[128]; //this is set to a static 128-byte value, omitting for brevity
unsigned long G = 2;

DH* dh = DH_new();
dh->p = BN_new();
dh->g = BN_new();

BN_set_word(dh->g, G);
BN_bin2bn(P, 128, dh->p);
if(DH_generate_key(dh))
{
   BN_bn2bin(dh->pub_key, publicKey);
}

This generates a 1024-bit public key.

I've tried using the DH classes in BouncyCastle, but for whatever reason I can't get it to give me a 1024-bit key, it wants to give me a 960 bit key instead. Possibly because I don't really know what I'm doing. I couldn't find much in the way of actual explanations of how the classes are supposed to be used.

Is it possible to use BouncyCastle DH classes to work the same as the OpenSSL DH code posted above? If not, is there another C# implementation that would work better?

Upvotes: 5

Views: 4583

Answers (1)

ntziolis
ntziolis

Reputation: 10221

Here is a working code example + article on CodeProject with an excellent rating:

http://www.codeproject.com/Articles/24632/Shared-Key-Generation-using-Diffie-Hellman

Upvotes: 3

Related Questions