Export (0) Print
Expand All

KeyedHashAlgorithm Class

Represents the abstract class from which all implementations of keyed hash algorithms must derive.

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

[ComVisibleAttribute(true)] 
public ref class KeyedHashAlgorithm abstract : public HashAlgorithm
/** @attribute ComVisibleAttribute(true) */ 
public abstract class KeyedHashAlgorithm extends HashAlgorithm
ComVisibleAttribute(true) 
public abstract class KeyedHashAlgorithm extends HashAlgorithm
Not applicable.

Hash functions map binary strings of an arbitrary length to small binary strings of a fixed length. A cryptographic hash function has the property that it is computationally infeasible to find two distinct inputs that hash to the same value. Small changes to the data result in large, unpredictable changes in the hash.

A keyed hash algorithm is a key-dependent, one-way hash function used as a message authentication code. Only someone who knows the key can verify the hash. Keyed hash algorithms provide authenticity without secrecy.

Hash functions are commonly used with digital signatures and for data integrity. The HMACSHA1 class is an example of a keyed hash algorithm.

The following code example demonstrates how to derive from the KeyedHashAlgorithm class.

#using <System.dll>
#using "contosokeyedhash.dll"
using namespace Contoso;
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections;
using namespace System::Security::Cryptography;

namespace Contoso
{
   ref class EncodeWithContoso
   {
   public:
      [STAThread]
      static void Main()
      {
         EncodeMessage();
         EncodeStream();
         Console::WriteLine( L"This sample completed successfully; "
         L"press Enter to exit" );
         Console::ReadLine();
      }

   private:
      // Compute the hash for a ContosoKeyedHash that has transformed a
      // file stream.
      static void EncodeStream()
      {
         array<Byte>^keyData = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( keyData );
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyData );

         String^ filePath = (String::Concat(
            System::IO::Directory::GetCurrentDirectory(), L"\\members.txt" ));
         try
         {
            FileStream^ fileStream = gcnew FileStream(
               filePath,FileMode::Open,FileAccess::Read );
            localCrypto->ComputeHash( fileStream );

            SummarizeMAC( localCrypto,
               L"ContosoKeyedHash after encoding a file stream." );
         }
         catch ( FileNotFoundException^ ) 
         {
            Console::WriteLine( L"The specified path was not found: {0}", filePath );
         }
      }

      // Compute the hash for a ContosoKeyedHash that has transformed
      // a byte array.
      static void EncodeMessage()
      {
         array<Byte>^ keyData = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( keyData );
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyData );
         
         String^ message = L"Hello World.";
         array<Byte>^ encodedMessage = EncodeBytes(
            Encoding::ASCII->GetBytes( message ) );
         localCrypto->ComputeHash( encodedMessage );
         
         SummarizeMAC( localCrypto, L"ContosoKeyedHash after encoding a message." );
      }


      // Transform the byte array using ContosoKeyedHash,
      // then summarize its properties.
      static array<Byte>^ EncodeBytes( array<Byte>^ sourceBytes )
      {
         int currentPosition = 0;
         array<Byte>^targetBytes = gcnew array<Byte>(1024);
         int sourceByteLength = sourceBytes->Length;
         
         // Create an encryptor with a random key and the
         // KeyedHashAlgorithm class name.
         array<Byte>^ key = gcnew array<Byte>(24);
         RandomNumberGenerator::Create()->GetBytes( key );
         String^ keyedHashName = L"System.Security.Cryptography.KeyedHashAlgorithm";
         ContosoKeyedHash^ localCrypto = gcnew ContosoKeyedHash( keyedHashName,key );
         
         // Retrieve the block size to read the bytes.
         int inputBlockSize = localCrypto->InputBlockSize;

         try
         {
            // Determine if multiple blocks can be transformed.
            if ( localCrypto->CanTransformMultipleBlocks )
            {
               int numBytesRead = 0;
               while ( sourceByteLength - currentPosition >= inputBlockSize )
               {
                  // Transform the bytes from the currentposition in the
                  // sourceBytes array, writing the bytes to the
                  // targetBytes array.
                  numBytesRead = localCrypto->TransformBlock(
                     sourceBytes,
                     currentPosition,
                     inputBlockSize,
                     targetBytes,
                     currentPosition );

                  // Advance the current position in the source array.
                  currentPosition += numBytesRead;
               }
               
               // Transform the final block of bytes.
               array<Byte>^ finalBytes = localCrypto->TransformFinalBlock(
                  sourceBytes,
                  currentPosition,
                  sourceByteLength - currentPosition );

               // Copy the contents of the finalBytes array to the
               // targetBytes array.
               finalBytes->CopyTo( targetBytes, currentPosition );
            }
         }
         catch ( Exception^ ex ) 
         {
            Console::WriteLine( L"Caught unexpected exception:{0}",
               ex->ToString() );
         }
         
         // Find the length of valid bytes (those without zeros).
         IEnumerator^ enum1 = targetBytes->GetEnumerator();
         int i = 0;
         while ( enum1->MoveNext() )
         {
            if ( enum1->Current->ToString()->Equals( L"0" ) )
            {
               break;
            }

            i++;
         }
         
         // Compute the hash based on the valid bytes in the array.
         localCrypto->ComputeHash( targetBytes, 0, i );

         SummarizeMAC( localCrypto, L"ContosoKeyedHash after computing "
         L"hash for specified region of byte array" );
         
         // Determine if the current transform can be reused.
         if (  !localCrypto->CanReuseTransform )
         {
            // Free up any used resources.
            localCrypto->Clear();

            localCrypto->Initialize();
         }
         
         // Create a new array with the number of valid bytes.
         array<Byte>^returnedArray = gcnew array<Byte>(i);
         for ( int j = 0; j < i; j++ )
         {
            returnedArray[ j ] = targetBytes[ j ];

         }
         return returnedArray;
      }

      // Write a summary of the specified ContosoKeyedHash to the
      // console window.
      static void SummarizeMAC( ContosoKeyedHash^ localCrypto,
         String^ description )
      {
         String^ classDescription = localCrypto->ToString();

         array<Byte>^computedHash = localCrypto->Hash;

         int hashSize = localCrypto->HashSize;

         int outputBlockSize = localCrypto->OutputBlockSize;

         // Retrieve the key used in the hash algorithm.
         array<Byte>^key = localCrypto->Key;

         Console::WriteLine( L"\n**********************************" );
         Console::WriteLine( classDescription );
         Console::WriteLine( description );
         Console::WriteLine( L"----------------------------------" );
         Console::WriteLine( L"The size of the computed hash : {0}",
            hashSize );
         Console::WriteLine( L"The key used in the hash algorithm : {0}",
            Encoding::ASCII->GetString( key ) );
         Console::WriteLine( L"The value of the computed hash : {0}",
            Encoding::ASCII->GetString( computedHash ) );
      }
   };
}

int main()
{
   EncodeWithContoso::Main();
}

import System.*;
import System.IO.*;
import System.Text.*;
import System.Collections.*;
import System.Security.Cryptography.*;

class EncodeWithContoso
{
    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        EncodeMessage();
        EncodeStream();
        Console.WriteLine("This sample completed successfully; " 
            + "press Enter to exit");
        Console.ReadLine();
    } //main

    // Compute the hash for a ContosoKeyedHash that has transformed a
    // file stream.
    private static void EncodeStream()
    {
        ubyte keyData[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(keyData);
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);
        String filePath = System.IO.Directory.GetCurrentDirectory() 
            + "\\members.txt";
        try {
            FileStream fileStream = new FileStream(filePath, FileMode.Open, 
                FileAccess.Read);
            localCrypto.ComputeHash(fileStream);
            SummarizeMAC(localCrypto, 
                "ContosoKeyedHash after encoding a file stream.");
        }
        catch (FileNotFoundException exp) {
            Console.WriteLine("The specified path was not found: " + filePath);
        }
    } //EncodeStream

    // Compute the hash for a ContosoKeyedHash that has transformed
    // a byte array.
    private static void EncodeMessage()
    {
        ubyte keyData[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(keyData);
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);
        String message = "Hello World.";
        ubyte encodedMessage[] = EncodeBytes(Encoding.get_ASCII().
            GetBytes(message));
        localCrypto.ComputeHash(encodedMessage);
        SummarizeMAC(localCrypto, 
            "ContosoKeyedHash after encoding a message.");
    } //EncodeMessage

    // Transform the byte array using ContosoKeyedHash,
    // then summarize its properties.
    private static ubyte[] EncodeBytes(ubyte sourceBytes[])
    {
        int currentPosition = 0;
        ubyte targetBytes[] = new ubyte[1024];
        int sourceByteLength = sourceBytes.get_Length();
        // Create an encryptor with a random key and the
        // KeyedHashAlgorithm class name.
        ubyte key[] = new ubyte[24];
        RandomNumberGenerator.Create().GetBytes(key);
        String keyedHashName = "System.Security.Cryptography.KeyedHashAlgorithm";
        ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyedHashName, key);
        // Retrieve the block size to read the bytes.
        int inputBlockSize = localCrypto.get_InputBlockSize();
        try {
            // Determine if multiple blocks can be transformed.
            if (localCrypto.get_CanTransformMultipleBlocks()) {
                int numBytesRead = 0;
                while (sourceByteLength - currentPosition >= inputBlockSize) {
                    // Transform the bytes from the currentposition in the
                    // sourceBytes array, writing the bytes to the 
                    // targetBytes array.
                    numBytesRead = localCrypto.TransformBlock(sourceBytes, 
                        currentPosition, inputBlockSize, targetBytes, 
                        currentPosition);
                    // Advance the current position in the source array.
                    currentPosition += numBytesRead;
                }
                
                // Transform the final block of bytes.
                ubyte finalBytes[] = localCrypto.TransformFinalBlock(sourceBytes, 
                      currentPosition, sourceByteLength - currentPosition);

                // Copy the contents of the finalBytes array to the
                // targetBytes array.
                finalBytes.CopyTo(targetBytes, currentPosition);
            }
        }
        catch (System.Exception ex) {
            Console.WriteLine("Caught unexpected exception:" + ex.ToString());
        }
        // Find the length of valid bytes (those without zeros).
        IEnumerator enum1 = targetBytes.GetEnumerator();
        int i = 0;
        while (enum1.MoveNext()) {
            if (enum1.get_Current().ToString().Equals("0")) {
                break;
            }
            i++;
        }
        // Compute the hash based on the valid bytes in the array.
        localCrypto.ComputeHash(targetBytes, 0, i);

        SummarizeMAC(localCrypto, "ContosoKeyedHash after computing " 
            + "hash for specified region of byte array");
        
        // Determine if the current transform can be reused.
        if (!(localCrypto.get_CanReuseTransform())) {
            // Free up any used resources.
            localCrypto.Clear();

            localCrypto.Initialize();
        }
        // Create a new array with the number of valid bytes.
        ubyte returnedArray[] = new ubyte[i];
        for (int j = 0; j < i; j++) {
            returnedArray.set_Item(j, targetBytes.get_Item(j));
        }
        return returnedArray;
    } //EncodeBytes

    // Write a summary of the specified ContosoKeyedHash to the
    // console window.
    private static void SummarizeMAC(ContosoKeyedHash localCrypto, 
        String description)
    {
        String classDescription = localCrypto.ToString();

        ubyte computedHash[] = localCrypto.get_Hash();

        int hashSize = localCrypto.get_HashSize();

        int outputBlockSize = localCrypto.get_OutputBlockSize();

        // Retrieve the key used in the hash algorithm.
        ubyte key[] = localCrypto.get_Key();

        Console.WriteLine("\n**********************************");
        Console.WriteLine(classDescription);
        Console.WriteLine(description);
        Console.WriteLine("----------------------------------");
        Console.WriteLine("The size of the computed hash : " + hashSize);
        Console.WriteLine("The key used in the hash algorithm : " 
            + Encoding.get_ASCII().GetString(key));
        Console.WriteLine("The value of the computed hash : " 
            + Encoding.get_ASCII().GetString(computedHash));
    } //SummarizeMAC
} //EncodeWithContoso

using namespace System;
using namespace System::Security::Cryptography;

namespace Contoso
{
   public ref class ContosoKeyedHash: public KeyedHashAlgorithm
   {
   private:
      KeyedHashAlgorithm^ keyedCrypto;

   public:
      ContosoKeyedHash( array<Byte>^ rgbKey )
      {
         Init( L"System.Security.Cryptography.KeyedHashAlgorithm", rgbKey );
      }

      ContosoKeyedHash( String^ keyedHashName, array<Byte>^ rgbKey )
      {
         Init( keyedHashName, rgbKey );
      }

      void Init( String^ keyedHashName, array<Byte>^ rgbKey )
      {
         // Make sure we know which algorithm to use
         if ( rgbKey != nullptr )
         {
            KeyValue = rgbKey;
            HashSizeValue = 160;
            
            // Create a KeyedHashAlgorithm encryptor
            if ( keyedHashName == nullptr )
            {
               
               keyedCrypto = KeyedHashAlgorithm::Create();
            }
            else
            {
               keyedCrypto = KeyedHashAlgorithm::Create( keyedHashName );
            }
         }
         else
         {
            throw gcnew ArgumentNullException( L"rgbKey" );
         }
      }

      // Override abstract methods from the HashAlgorithm class.
      virtual void Initialize() override {}

      property array<Byte>^ Key 
      {
         virtual array<Byte>^ get() override
         {
            return dynamic_cast<array<Byte>^>(keyedCrypto->Key->Clone());
         }

         virtual void set( array<Byte>^value ) override
         {
            keyedCrypto->Key = dynamic_cast<array<Byte>^>(value->Clone());
         }
      }

   protected:
      virtual void HashCore( array<Byte>^ , int /*ibStart*/, int /*cbSize*/ ) override {}

      virtual array<Byte>^ HashFinal() override
      {
         return gcnew array<Byte>(0);
      }
   };
}

import System.*;
import System.Security.Cryptography.*;

class ContosoKeyedHash extends KeyedHashAlgorithm
{
    private KeyedHashAlgorithm keyedCrypto;

    public ContosoKeyedHash(ubyte rgbKey[])
    {
        this("System.Security.Cryptography.KeyedHashAlgorithm", rgbKey);
    } //ContosoKeyedHash

    public ContosoKeyedHash(String keyedHashName, ubyte rgbKey[])
    {
        // Make sure we know which algorithm to use
        if (rgbKey != null) {
            KeyValue = rgbKey;
            HashSizeValue = 160;
            // Create a KeyedHashAlgorithm encryptor
            if (keyedHashName == null) {
                keyedCrypto = KeyedHashAlgorithm.Create();
            }
            else {
                keyedCrypto = KeyedHashAlgorithm.Create(keyedHashName);
            }
        } 
        else {
            throw new ArgumentNullException("rgbKey");
        }
    } //ContosoKeyedHash

    // Override abstract methods from the HashAlgorithm class.
    public void Initialize()
    {
    } //Initialize 

    /** @property 
     */
    public ubyte[] get_Key()
    {
        return (ubyte[])keyedCrypto.get_Key().Clone();
    } //get_Key

    /** @property 
     */
    public void set_Key(ubyte value[])
    {
        keyedCrypto.set_Key((ubyte[])(value.Clone()));
    } //set_Key

    protected void HashCore(ubyte rgbData[], int ibStart, int cbSize)
    {
    } //HashCore

    protected ubyte[] HashFinal()
    {
        return new ubyte[0];
    } //HashFinal
} //ContosoKeyedHash

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

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft