ECDiffieHellmanCng Class
TOC
Collapse the table of content
Expand the table of content

ECDiffieHellmanCng Class

.NET Framework (current version)
 

Provides a Cryptography Next Generation (CNG) implementation of the Elliptic Curve Diffie-Hellman (ECDH) algorithm. This class is used to perform cryptographic operations.

Namespace:   System.Security.Cryptography
Assembly:  System.Core (in System.Core.dll)


[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class ECDiffieHellmanCng : ECDiffieHellman

NameDescription
System_CAPS_pubmethodECDiffieHellmanCng()

Initializes a new instance of the ECDiffieHellmanCng class with a random key pair.

System_CAPS_pubmethodECDiffieHellmanCng(CngKey)

Initializes a new instance of the ECDiffieHellmanCng class by using the specified CngKey object.

System_CAPS_pubmethodECDiffieHellmanCng(Int32)

Initializes a new instance of the ECDiffieHellmanCng class with a random key pair, using the specified key size.

NameDescription
System_CAPS_pubpropertyHashAlgorithm

Gets or sets the hash algorithm to use when generating key material.

System_CAPS_pubpropertyHmacKey

Gets or sets the Hash-based Message Authentication Code (HMAC) key to use when deriving key material.

System_CAPS_pubpropertyKey

Specifies the CngKey that is used by the current object for cryptographic operations.

System_CAPS_pubpropertyKeyDerivationFunction

Gets or sets the key derivation function for the ECDiffieHellmanCng class.

System_CAPS_pubpropertyKeyExchangeAlgorithm

Gets the name of the key exchange algorithm.(Inherited from ECDiffieHellman.)

System_CAPS_pubpropertyKeySize

Gets or sets the size, in bits, of the key modulus used by the asymmetric algorithm.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubpropertyLabel

Gets or sets the label value that is used for key derivation.

System_CAPS_pubpropertyLegalKeySizes

Gets the key sizes that are supported by the asymmetric algorithm.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubpropertyPublicKey

Gets the public key that can be used by another ECDiffieHellmanCng object to generate a shared secret agreement.(Overrides ECDiffieHellman.PublicKey.)

System_CAPS_pubpropertySecretAppend

Gets or sets a value that will be appended to the secret agreement when generating key material.

System_CAPS_pubpropertySecretPrepend

Gets or sets a value that will be added to the beginning of the secret agreement when deriving key material.

System_CAPS_pubpropertySeed

Gets or sets the seed value that will be used when deriving key material.

System_CAPS_pubpropertySignatureAlgorithm

Gets the name of the signature algorithm.(Inherited from ECDiffieHellman.)

System_CAPS_pubpropertyUseSecretAgreementAsHmacKey

Gets a value that indicates whether the secret agreement is used as a Hash-based Message Authentication Code (HMAC) key to derive key material.

NameDescription
System_CAPS_pubmethodClear()

Releases all resources used by the AsymmetricAlgorithm class.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubmethodDeriveKeyMaterial(CngKey)

Derives the key material that is generated from the secret agreement between two parties, given a CngKey object that contains the second party's public key.

System_CAPS_pubmethodDeriveKeyMaterial(ECDiffieHellmanPublicKey)

Derives the key material that is generated from the secret agreement between two parties, given an ECDiffieHellmanPublicKey object that contains the second party's public key. (Overrides ECDiffieHellman.DeriveKeyMaterial(ECDiffieHellmanPublicKey).)

System_CAPS_pubmethodDeriveSecretAgreementHandle(CngKey)

Gets a handle to the secret agreement generated between two parties, given a CngKey object that contains the second party's public key.

System_CAPS_pubmethodDeriveSecretAgreementHandle(ECDiffieHellmanPublicKey)

Gets a handle to the secret agreement generated between two parties, given an ECDiffieHellmanPublicKey object that contains the second party's public key.

System_CAPS_pubmethodDispose()

Releases all resources used by the current instance of the AsymmetricAlgorithm class.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodFromXmlString(String)

This method is not implemented.(Overrides AsymmetricAlgorithm.FromXmlString(String).)

System_CAPS_pubmethodFromXmlString(String, ECKeyXmlFormat)

Deserializes the key information from an XML string by using the specified format.

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodToXmlString(Boolean)

This method is not implemented.(Overrides AsymmetricAlgorithm.ToXmlString(Boolean).)

System_CAPS_pubmethodToXmlString(ECKeyXmlFormat)

Serializes the key information to an XML string by using the specified format.

The ECDiffieHellmanCng class enables two parties to exchange private key material even if they are communicating through a public channel. Both parties can calculate the same secret value, which is referred to as the secret agreement in the managed Diffie-Hellman classes. The secret agreement can then be used for a variety of purposes, including as a symmetric key. However, instead of exposing the secret agreement directly, the ECDiffieHellmanCng class does some post-processing on the agreement before providing the value. This post processing is referred to as the key derivation function (KDF); you can select which KDF you want to use and set its parameters through a set of properties on the instance of the Diffie-Hellman object.

Key derivation function

Properties

Hash

HashAlgorithm - The hash algorithm that is used to process the secret agreement.

SecretPrepend - An optional byte array to prepend to the secret agreement before hashing it.

SecretAppend - An optional byte array to append to the secret agreement before hashing it.

Hmac

HashAlgorithm - The hash algorithm that is used to process the secret agreement.

SecretPrepend- An optional byte array to prepend to the secret agreement before hashing it.

SecretAppend - An optional byte array to append to the secret agreement before hashing it.

Tls

Label - The label for key derivation.

Seed - The seed for key derivation.

The result of passing the secret agreement through the key derivation function is a byte array that may be used as key material for your application. The number of bytes of key material generated is dependent on the key derivation function; for example, SHA-256 will generate 256 bits of key material, whereas SHA-512 will generate 512 bits of key material.The basic flow of an ECDH key exchange is as follows:

  1. Alice and Bob create a key pair to use for the Diffie-Hellman key exchange operation

  2. Alice and Bob configure the KDF using parameters the agree on.

  3. Alice sends Bob her public key.

  4. Bob sends Alice his public key.

  5. Alice and Bob use each other's public keys to generate the secret agreement, and apply the KDF to the secret agreement to generate key material.

The following example shows how to use the ECDiffieHellmanCng class to establish a key exchange and how to use that key to encrypt a message that can be sent over a public channel and decrypted by the receiver.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;


class Alice
{
    public static byte[] alicePublicKey;

    public static void Main(string[] args)
    {
        using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng())
        {

            alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            alice.HashAlgorithm = CngAlgorithm.Sha256;
            alicePublicKey = alice.PublicKey.ToByteArray();
            Bob bob = new Bob();
            CngKey k = CngKey.Import(bob.bobPublicKey, CngKeyBlobFormat.EccPublicBlob);
            byte[] aliceKey = alice.DeriveKeyMaterial(CngKey.Import(bob.bobPublicKey, CngKeyBlobFormat.EccPublicBlob));
            byte[] encryptedMessage = null;
            byte[] iv = null;
            Send(aliceKey, "Secret message", out encryptedMessage, out iv);
            bob.Receive(encryptedMessage, iv);
        }

    }

    private static void Send(byte[] key, string secretMessage, out byte[] encryptedMessage, out byte[] iv)
    {
        using (Aes aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            iv = aes.IV;

            // Encrypt the message
            using (MemoryStream ciphertext = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] plaintextMessage = Encoding.UTF8.GetBytes(secretMessage);
                cs.Write(plaintextMessage, 0, plaintextMessage.Length);
                cs.Close();
                encryptedMessage = ciphertext.ToArray();
            }
        }
    }

}
public class Bob 
{
    public byte[] bobPublicKey;
    private byte[] bobKey;
    public Bob()
    {
        using (ECDiffieHellmanCng bob = new ECDiffieHellmanCng())
        {

            bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            bob.HashAlgorithm = CngAlgorithm.Sha256;
            bobPublicKey = bob.PublicKey.ToByteArray();
            bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob));

        }
    }

    public void Receive(byte[] encryptedMessage, byte[] iv)
    {

        using (Aes aes = new AesCryptoServiceProvider())
        {
            aes.Key = bobKey;
            aes.IV = iv;
            // Decrypt the message
            using (MemoryStream plaintext = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(encryptedMessage, 0, encryptedMessage.Length);
                    cs.Close();
                    string message = Encoding.UTF8.GetString(plaintext.ToArray());
                    Console.WriteLine(message);
                }
            }
        }
    }

}

.NET Framework
Available since 3.5

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft