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

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 abstract class KeyedHashAlgorithm : 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;
using System.IO;
using System.Text;
using System.Collections;
using System.Security.Cryptography;

namespace Contoso
{
    class EncodeWithContoso
    {
        [STAThread]
        static void Main(string[] args)
        {
            EncodeMessage();
            EncodeStream();

            Console.WriteLine("This sample completed successfully; " + 
                "press Enter to exit");
            Console.ReadLine();
        }

        // Compute the hash for a ContosoKeyedHash that has transformed a
        // file stream.
        private static void EncodeStream()
        {
            byte[] keyData = new byte[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)
            {
                Console.WriteLine("The specified path was not found: " +
                    filePath);
            }
        }

        // Compute the hash for a ContosoKeyedHash that has transformed
        // a byte array.
        private static void EncodeMessage()
        {
            byte[] keyData = new byte[24];
            RandomNumberGenerator.Create().GetBytes(keyData);
            ContosoKeyedHash localCrypto = new ContosoKeyedHash(keyData);

            string message = "Hello World.";
            byte[] encodedMessage = 
                EncodeBytes(Encoding.ASCII.GetBytes(message));

            localCrypto.ComputeHash(encodedMessage);

            SummarizeMAC(localCrypto, 
                "ContosoKeyedHash after encoding a message.");
        }
        
        // Transform the byte array using ContosoKeyedHash,
        // then summarize its properties.
        private static byte[] EncodeBytes(byte[] sourceBytes)
        {
            int currentPosition = 0;
            byte[] targetBytes = new byte[1024];
            int sourceByteLength = sourceBytes.Length;

            // Create an encryptor with a random key and the
            // KeyedHashAlgorithm class name.
            byte[] key = new byte[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.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.
                    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("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.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.CanReuseTransform)
            {
                // Free up any used resources.
                localCrypto.Clear();

                localCrypto.Initialize();
            }

            // Create a new array with the number of valid bytes.
            byte[] returnedArray = new 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.
        private static void SummarizeMAC(
            ContosoKeyedHash localCrypto,
            string description)
        {
            string classDescription = localCrypto.ToString();

            byte[] computedHash = localCrypto.Hash;

            int hashSize = localCrypto.HashSize;

            int outputBlockSize = localCrypto.OutputBlockSize;

            // Retrieve the key used in the hash algorithm.
            byte[] key = localCrypto.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.ASCII.GetString(key));
            Console.WriteLine("The value of the computed hash : " + 
                Encoding.ASCII.GetString(computedHash));
        }
    }
}

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 System;
using System.Security.Cryptography;

namespace Contoso
{
    class ContosoKeyedHash : KeyedHashAlgorithm
    {
        private KeyedHashAlgorithm keyedCrypto;

        public ContosoKeyedHash(byte[] rgbKey) 
            : this("System.Security.Cryptography.KeyedHashAlgorithm", rgbKey)
        {

        }

        public ContosoKeyedHash(String keyedHashName, byte[] 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");
            }
        }

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


        public override byte[] Key
        {
            get
            {
                return (byte[]) keyedCrypto.Key.Clone();
            }
            set
            {
                keyedCrypto.Key = (byte[]) value.Clone();
            }
        }

        protected override void HashCore(
            byte[] rgbData, 
            int ibStart, 
            int cbSize)
        {

        }
        protected override byte[] HashFinal()
        {
            return new 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
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.