Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

ECDiffieHellmanCng Class

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

The ECDiffieHellmanCng type exposes the following members.

  NameDescription
Public methodECDiffieHellmanCng()Initializes a new instance of the ECDiffieHellmanCng class with a random key pair.
Public methodECDiffieHellmanCng(CngKey)Initializes a new instance of the ECDiffieHellmanCng class by using the specified CngKey object.
Public methodECDiffieHellmanCng(Int32)Initializes a new instance of the ECDiffieHellmanCng class with a random key pair, using the specified key size.
Top
  NameDescription
Public propertyHashAlgorithmGets or sets the hash algorithm to use when generating key material.
Public propertyHmacKeyGets or sets the Hash-based Message Authentication Code (HMAC) key to use when deriving key material.
Public propertyKeySpecifies the CngKey that is used by the current object for cryptographic operations.
Public propertyKeyDerivationFunctionGets or sets the key derivation function for the ECDiffieHellmanCng class.
Public propertyKeyExchangeAlgorithmGets the name of the key exchange algorithm. (Inherited from ECDiffieHellman.)
Public propertyKeySizeGets or sets the size, in bits, of the key modulus used by the asymmetric algorithm. (Inherited from AsymmetricAlgorithm.)
Public propertyLabelGets or sets the label value that is used for key derivation.
Public propertyLegalKeySizesGets the key sizes that are supported by the asymmetric algorithm. (Inherited from AsymmetricAlgorithm.)
Public propertyPublicKeyGets the public key that can be used by another ECDiffieHellmanCng object to generate a shared secret agreement. (Overrides ECDiffieHellman.PublicKey.)
Public propertySecretAppendGets or sets a value that will be appended to the secret agreement when generating key material.
Public propertySecretPrependGets or sets a value that will be added to the beginning of the secret agreement when deriving key material.
Public propertySeedGets or sets the seed value that will be used when deriving key material.
Public propertySignatureAlgorithmGets the name of the signature algorithm. (Inherited from ECDiffieHellman.)
Public propertyUseSecretAgreementAsHmacKeyGets a value that indicates whether the secret agreement is used as a Hash-based Message Authentication Code (HMAC) key to derive key material.
Top
  NameDescription
Public methodClearReleases all resources used by the AsymmetricAlgorithm class. (Inherited from AsymmetricAlgorithm.)
Public methodDeriveKeyMaterial(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.
Public methodDeriveKeyMaterial(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).)
Public methodDeriveSecretAgreementHandle(CngKey)Gets a handle to the secret agreement generated between two parties, given a CngKey object that contains the second party's public key.
Public methodDeriveSecretAgreementHandle(ECDiffieHellmanPublicKey)Gets a handle to the secret agreement generated between two parties, given an ECDiffieHellmanPublicKey object that contains the second party's public key.
Public methodDispose()Releases all resources used by the current instance of the AsymmetricAlgorithm class. (Inherited from AsymmetricAlgorithm.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodFromXmlString(String)This method is not implemented. (Overrides AsymmetricAlgorithm.FromXmlString(String).)
Public methodFromXmlString(String, ECKeyXmlFormat)Deserializes the key information from an XML string by using the specified format.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodToXmlString(Boolean)This method is not implemented. (Overrides AsymmetricAlgorithm.ToXmlString(Boolean).)
Public methodToXmlString(ECKeyXmlFormat)Serializes the key information to an XML string by using the specified format.
Top

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.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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

Supported in: 4.5.1, 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.