Click here to Skip to main content
13,502,268 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

7.8K views
357 downloads
18 bookmarked
Posted 5 Dec 2017

Implement Diffie-Hellman in C#

, 5 Dec 2017
Rate this:
Please Sign up or sign in to vote.
Lets looks at the Diffie-Hellman key exchange to securely send private information over a public channel.

Introduction

Lets create a cryptographic class which has two methods - encrypt and decrypt. These two methods will allow you to exchange your public key with the other party and decrypt the secret messages with your private key. The secret message will be encrypted using standard AES encryption.

Table of Contents

  1. Glossary
  2. Visualization of Diffie-Hellman
  3. Using the code
    • Step 01 - Create a Class Library
    • Step 02 - Add fields
    • Step 03 - Add a constructor
    • Step 04 - Expose Public Key and IV
    • Step 05 - Create an Encrypt method
    • Step 06 - Create a Decrypt method
    • Step 07 - Dispose unmanaged resources
    • Step 08 - Create a test class
  4. Final Words

Glossary

AES (Advanced Encryption Standard) - Originally called "Rijndael", is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001. The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data.

CNG (Cryptography Next Generation) - A cryptographic development platform that allows developers to create, update, and use custom cryptography algorithms in cryptography-related applications.

Diffie-Hellman - A method of securely exchanging cryptographic keys over a public channel and was one of the first public-key protocols as originally conceptualized by Ralph Merkle and named after Whitfield Diffie and Martin Hellman.

IV (Initialization Vector) - An arbitrary number that can be used along with a secret key for data encryption. This number, also called a nonce, is employed only one time in any session. (We will be using the other party's IV and public key to decrypt the secret message.)

Visualization of Diffie-Hellman

Using the Code

Step 01 - Create a Class Library

Open Visual Studio and go to "File > New > Project" and select "Class Library".

Give your project a name (e.g. SecureKeyExchange) and click "OK".

After you project is created, rename the "Class1.cs" file to "DiffieHellman.cs".

 

Step 02 - Add fields

We need to add three fields; one that contains a reference to the Aes-class, the second field to store a reference to the ECDiffieHellmanCng-class and the last fields to store our public key.

The Aes-reference will be used to encrypt/decrypt the messages. The ECDiffieHellmanCng-reference will be used to create a derived key between the two parties.

Add the following three fields to your class:

private Aes aes = null;
private ECDiffieHellmanCng diffieHellman = null;

private readonly byte[] publicKey;

 

Step 03 - Add a constructor

Our constructor should now initialize these fields:

public DiffieHellman()
{
    this.aes = new AesCryptoServiceProvider();

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

    // This is the public key we will send to the other party
    this.publicKey = this.diffieHellman.PublicKey.ToByteArray();
}

Once the ECDiffieHellmanCng instance has been initialized, we can set our publicKey field to the PublicKey of the ECDiffieHellmanCng instance. We are going to send this public key along with the secret message to the other party.

Step 04 - Expose Public Key and IV

Lets expose both our public key and IV through properties. Add the following properties respectively:

public byte[] PublicKey
{
    get
    {
        return this.publicKey;
    }
}

public byte[] IV
{
    get
    {
        return this.aes.IV;
    }
}

These properties will be sent to the other party to decrypt the secret message using their own private key.

Step 05 - Create an Encrypt method

We are going to create a method that takes the public key of the other party as well as the secret message to encrypt.

We will use the other party's public key to generate a derived key (see "Common secret" in the paint analogy above) which will be used to encrypt the message. Add the Encrypt function:

public byte[] Encrypt(byte[] publicKey, string secretMessage)
{
    byte[] encryptedMessage;
    var key = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
    var derivedKey = this.diffieHellman.DeriveKeyMaterial(key); // "Common secret"

    this.aes.Key = derivedKey;

    using (var cipherText = new MemoryStream())
    {
        using (var encryptor = this.aes.CreateEncryptor())
        {
            using (var cryptoStream = new CryptoStream(cipherText, encryptor, CryptoStreamMode.Write))
            {
                byte[] ciphertextMessage = Encoding.UTF8.GetBytes(secretMessage);
                cryptoStream.Write(ciphertextMessage, 0, ciphertextMessage.Length);
            }
        }

        encryptedMessage = cipherText.ToArray();
    }

    return encryptedMessage;
}

Now our message is encrypted and we can send it to the other party. But first need to add a function to decrypt this secret message.

Step 06 - Create a Decrypt method

Our Decrypt function will take in 3 parameters: The public key and IV of the other party as well as the secret message. Lets add the function:

public string Decrypt(byte[] publicKey, byte[] encryptedMessage, byte[] iv)
{
    string decryptedMessage;
    var key = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
    var derivedKey = this.diffieHellman.DeriveKeyMaterial(key);

    this.aes.Key = derivedKey;
    this.aes.IV = iv;

    using (var plainText = new MemoryStream())
    {
        using (var decryptor = this.aes.CreateDecryptor())
        {
            using (var cryptoStream = new CryptoStream(plainText, decryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(encryptedMessage, 0, encryptedMessage.Length);
            }
        }

        decryptedMessage = Encoding.UTF8.GetString(plainText.ToArray());
    }

    return decryptedMessage;
}

We can now decrypt the secret message.

Step 07 - Dispose unmanaged resources

The last piece of code we still need to add is to implement the IDisposable interface to clean up our unmanaged resources.

Lets add the interface to our DiffieHellman class:

public class DiffieHellman : IDisposable

And add the implementation:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (this.aes != null)
            this.aes.Dispose();

        if (this.diffieHellman != null)
            this.diffieHellman.Dispose();
    }
}

Our class is complete. Now we need to create a test class to test our functionality.

Step 08 - Create a test class

Right click on the solution and select "Add > New Project > Unit Test Project" and give your project a name (e.g "SecureKeyExchange.Tests"). Rename your "UnitTest1.cs" to "DiffieHellmanTests.cs" and add a reference to the "SecureKeyExchange" project. To do this, right-click on the "References" node under the test project and select "Add Reference > Projects > Select the project > OK".

Add the following test method to our test class:

[TestMethod]
public void Encrypt_Decrypt()
{
    string text = "Hello World!";

    using (var bob = new DiffieHellman())
    {
        using (var alice = new DiffieHellman())
        {
            // Bob uses Alice's public key to encrypt his message.
            byte[] secretMessage = bob.Encrypt(alice.PublicKey, text);

            // Alice uses Bob's public key and IV to decrypt the secret message.
            string decryptedMessage = alice.Decrypt(bob.PublicKey, secretMessage, bob.IV);
        }
    }
}

We can now add a breakpoint and debug our test (press Ctrl+R,Ctrl+A) to see the results:

Final Words

The Diffie-Hellman key exchange allows us to send secret information over a public channel. In my next post, we will look at how to implement this into a real world scenario.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pierre Nortje
Software Developer BeingIT
South Africa South Africa
I am a software developer that loves creating new things, solving solutions and reading about the latest technologies. I am currently working on MVC projects, creating .NET APIs, deploying applications, writing SQL queries, debugging Windows Services, developing Xamarin mobile applications and working with a bunch of great people. Outside of work I am a brother, father and a grateful husband.

You may also be interested in...

Comments and Discussions

 
PraiseNice implementation Pin
asiwel6-Dec-17 12:18
memberasiwel6-Dec-17 12:18 
GeneralRe: Nice implementation Pin
Pierre Nortje6-Dec-17 22:07
professionalPierre Nortje6-Dec-17 22:07 
QuestionRe: Nice implementation Pin
asiwel7-Dec-17 11:26
memberasiwel7-Dec-17 11:26 
AnswerRe: Nice implementation Pin
Pierre Nortje8-Dec-17 1:50
professionalPierre Nortje8-Dec-17 1:50 
GeneralRe: Nice implementation Pin
asiwel8-Dec-17 15:01
memberasiwel8-Dec-17 15:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180417.1 | Last Updated 5 Dec 2017
Article Copyright 2017 by Pierre Nortje
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid