KeyedHashAlgorithm Class

Definition

代表基底類別,金鑰雜湊演算法的所有實作必須從它衍生。Represents the abstract class from which all implementations of keyed hash algorithms must derive.

public ref class KeyedHashAlgorithm abstract : System::Security::Cryptography::HashAlgorithm
public abstract class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
type KeyedHashAlgorithm = class
    inherit HashAlgorithm
Public MustInherit Class KeyedHashAlgorithm
Inherits HashAlgorithm
Inheritance
KeyedHashAlgorithm
Derived
Attributes

Examples

下列程式碼範例示範如何從 KeyedHashAlgorithm 類別衍生。The following code example demonstrates how to derive from the KeyedHashAlgorithm class.

using System;
using System.Security.Cryptography;

public class TestHMACMD5
{
    static private void PrintByteArray(Byte[] arr)
    {
        int i;
        Console.WriteLine("Length: " + arr.Length);
        for (i = 0; i < arr.Length; i++)
        {
            Console.Write("{0:X}", arr[i]);
            Console.Write("    ");
            if ((i + 9) % 8 == 0) Console.WriteLine();
        }
        if (i % 8 != 0) Console.WriteLine();
    }
    public static void Main()
    {
        // Create a key.
        byte[] key1 = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
        // Pass the key to the constructor of the HMACMD5 class.
        HMACMD5 hmac1 = new HMACMD5(key1);

        // Create another key.
        byte[] key2 = System.Text.Encoding.ASCII.GetBytes("KeyString");
        // Pass the key to the constructor of the HMACMD5 class.
        HMACMD5 hmac2 = new HMACMD5(key2);

        // Encode a string into a byte array, create a hash of the array,
        // and print the hash to the screen.
        byte[] data1 = System.Text.Encoding.ASCII.GetBytes("Hi There");
        PrintByteArray(hmac1.ComputeHash(data1));

        // Encode a string into a byte array, create a hash of the array,
        // and print the hash to the screen.
        byte[] data2 = System.Text.Encoding.ASCII.GetBytes("This data will be hashed.");
        PrintByteArray(hmac2.ComputeHash(data2));
    }
}
public class HMACMD5 : KeyedHashAlgorithm
{
    private MD5 hash1;
    private MD5 hash2;
    private bool bHashing = false;

    private byte[] rgbInner = new byte[64];
    private byte[] rgbOuter = new byte[64];

    public HMACMD5(byte[] rgbKey)
    {
        HashSizeValue = 128;
        // Create the hash algorithms.
        hash1 = MD5.Create();
        hash2 = MD5.Create();
        // Get the key.
        if (rgbKey.Length > 64)
        {
            KeyValue = hash1.ComputeHash(rgbKey);
            // No need to call Initialize; ComputeHash does it automatically.
        }
        else
        {
            KeyValue = (byte[])rgbKey.Clone();
        }
        // Compute rgbInner and rgbOuter.
        int i = 0;
        for (i = 0; i < 64; i++)
        {
            rgbInner[i] = 0x36;
            rgbOuter[i] = 0x5C;
        }
        for (i = 0; i < KeyValue.Length; i++)
        {
            rgbInner[i] ^= KeyValue[i];
            rgbOuter[i] ^= KeyValue[i];
        }
    }

    public override byte[] Key
    {
        get { return (byte[])KeyValue.Clone(); }
        set
        {
            if (bHashing)
            {
                throw new Exception("Cannot change key during hash operation");
            }
            if (value.Length > 64)
            {
                KeyValue = hash1.ComputeHash(value);
                // No need to call Initialize; ComputeHash does it automatically.
            }
            else
            {
                KeyValue = (byte[])value.Clone();
            }
            // Compute rgbInner and rgbOuter.
            int i = 0;
            for (i = 0; i < 64; i++)
            {
                rgbInner[i] = 0x36;
                rgbOuter[i] = 0x5C;
            }
            for (i = 0; i < KeyValue.Length; i++)
            {
                rgbInner[i] ^= KeyValue[i];
                rgbOuter[i] ^= KeyValue[i];
            }
        }
    }
    public override void Initialize()
    {
        hash1.Initialize();
        hash2.Initialize();
        bHashing = false;
    }
    protected override void HashCore(byte[] rgb, int ib, int cb)
    {
        if (bHashing == false)
        {
            hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
            bHashing = true;
        }
        hash1.TransformBlock(rgb, ib, cb, rgb, ib);
    }

    protected override byte[] HashFinal()
    {
        if (bHashing == false)
        {
            hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
            bHashing = true;
        }
        // Finalize the original hash.
        hash1.TransformFinalBlock(new byte[0], 0, 0);
        // Write the outer array.
        hash2.TransformBlock(rgbOuter, 0, 64, rgbOuter, 0);
        // Write the inner hash and finalize the hash.
        hash2.TransformFinalBlock(hash1.Hash, 0, hash1.Hash.Length);
        bHashing = false;
        return hash2.Hash;
    }
}
Imports System.Security.Cryptography
 _

Public Class TestHMACMD5

    Private Shared Sub PrintByteArray(ByVal arr() As [Byte])
        Dim i As Integer
        Console.WriteLine(("Length: " + arr.Length.ToString()))
        For i = 0 To arr.Length - 1
            Console.Write("{0:X}", arr(i))
            Console.Write("    ")
            If (i + 9) Mod 8 = 0 Then
                Console.WriteLine()
            End If
        Next i
        If i Mod 8 <> 0 Then
            Console.WriteLine()
        End If
    End Sub

    Public Shared Sub Main()
        ' Create a key.
        Dim key1 As Byte() = {&HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB}
        ' Pass the key to the constructor of the HMACMD5 class.  
        Dim hmac1 As New HMACMD5(key1)

        ' Create another key.
        Dim key2 As Byte() = System.Text.Encoding.ASCII.GetBytes("KeyString")
        ' Pass the key to the constructor of the HMACMD5 class.  
        Dim hmac2 As New HMACMD5(key2)

        ' Encode a string into a byte array, create a hash of the array,
        ' and print the hash to the screen.
        Dim data1 As Byte() = System.Text.Encoding.ASCII.GetBytes("Hi There")
        PrintByteArray(hmac1.ComputeHash(data1))

        ' Encode a string into a byte array, create a hash of the array,
        ' and print the hash to the screen.
        Dim data2 As Byte() = System.Text.Encoding.ASCII.GetBytes("This data will be hashed.")
        PrintByteArray(hmac2.ComputeHash(data2))
    End Sub
End Class
 _

Public Class HMACMD5
    Inherits KeyedHashAlgorithm
    Private hash1 As MD5
    Private hash2 As MD5
    Private bHashing As Boolean = False

    Private rgbInner(64) As Byte
    Private rgbOuter(64) As Byte


    Public Sub New(ByVal rgbKey() As Byte)
        HashSizeValue = 128
        ' Create the hash algorithms.
        hash1 = MD5.Create()
        hash2 = MD5.Create()
        ' Get the key.
        If rgbKey.Length > 64 Then
            KeyValue = hash1.ComputeHash(rgbKey)
            ' No need to call Initialize; ComputeHash does it automatically.
        Else
            KeyValue = CType(rgbKey.Clone(), Byte())
        End If
        ' Compute rgbInner and rgbOuter.
        Dim i As Integer = 0
        For i = 0 To 63
            rgbInner(i) = &H36
            rgbOuter(i) = &H5C
        Next i
        i = 0
        For i = 0 To KeyValue.Length - 1
            rgbInner(i) = rgbInner(i) Xor KeyValue(i)
            rgbOuter(i) = rgbOuter(i) Xor KeyValue(i)
        Next i
    End Sub


    Public Overrides Property Key() As Byte()
        Get
            Return CType(KeyValue.Clone(), Byte())
        End Get
        Set(ByVal Value As Byte())
            If bHashing Then
                Throw New Exception("Cannot change key during hash operation")
            End If
            If value.Length > 64 Then
                KeyValue = hash1.ComputeHash(value)
                ' No need to call Initialize; ComputeHash does it automatically.
            Else
                KeyValue = CType(value.Clone(), Byte())
            End If
            ' Compute rgbInner and rgbOuter.
            Dim i As Integer = 0
            For i = 0 To 63
                rgbInner(i) = &H36
                rgbOuter(i) = &H5C
            Next i
            For i = 0 To KeyValue.Length - 1
                rgbInner(i) ^= KeyValue(i)
                rgbOuter(i) ^= KeyValue(i)
            Next i
        End Set
    End Property


    Public Overrides Sub Initialize()
        hash1.Initialize()
        hash2.Initialize()
        bHashing = False
    End Sub


    Protected Overrides Sub HashCore(ByVal rgb() As Byte, ByVal ib As Integer, ByVal cb As Integer)
        If bHashing = False Then
            hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0)
            bHashing = True
        End If
        hash1.TransformBlock(rgb, ib, cb, rgb, ib)
    End Sub


    Protected Overrides Function HashFinal() As Byte()
        If bHashing = False Then
            hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0)
            bHashing = True
        End If
        ' Finalize the original hash.
        hash1.TransformFinalBlock(New Byte(0) {}, 0, 0)
        ' Write the outer array.
        hash2.TransformBlock(rgbOuter, 0, 64, rgbOuter, 0)
        ' Write the inner hash and finalize the hash.
        hash2.TransformFinalBlock(hash1.Hash, 0, hash1.Hash.Length)
        bHashing = False
        Return hash2.Hash
    End Function
End Class

Remarks

雜湊函數會將任意長度的二進位字串對應至固定長度的小型二進位字串。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. HMACSHA1 類別是金鑰雜湊演算法的範例。The HMACSHA1 class is an example of a keyed hash algorithm.

由於 SHA1 的衝突問題,Microsoft 建議您使用以 SHA256 或更好的加密方式為基礎的安全性模型。Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better.

Constructors

KeyedHashAlgorithm()

KeyedHashAlgorithm 類別的新執行個體初始化。Initializes a new instance of the KeyedHashAlgorithm class.

Fields

HashSizeValue

代表計算出來之雜湊碼的大小,以位元為單位。Represents the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
HashValue

表示計算出來的雜湊碼的值。Represents the value of the computed hash code.

(Inherited from HashAlgorithm)
KeyValue

要使用於雜湊演算法的金鑰。The key to use in the hash algorithm.

State

表示雜湊計算的狀態。Represents the state of the hash computation.

(Inherited from HashAlgorithm)

Properties

CanReuseTransform

取得值,表示目前的轉換是否可重複使用。Gets a value indicating whether the current transform can be reused.

(Inherited from HashAlgorithm)
CanTransformMultipleBlocks

在衍生類別中覆寫時,取得值以指出是否可以轉換多個區塊。When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed.

(Inherited from HashAlgorithm)
Hash

取得計算出來之雜湊碼的值。Gets the value of the computed hash code.

(Inherited from HashAlgorithm)
HashSize

取得計算出來之雜湊碼的大小,以位元為單位。Gets the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
InputBlockSize

在衍生類別中覆寫時,取得輸入區塊的大小。When overridden in a derived class, gets the input block size.

(Inherited from HashAlgorithm)
Key

取得或設定要使用於雜湊演算法的金鑰。Gets or sets the key to use in the hash algorithm.

OutputBlockSize

在衍生類別中覆寫時,取得輸出區塊的大小。When overridden in a derived class, gets the output block size.

(Inherited from HashAlgorithm)

Methods

Clear()

釋放 HashAlgorithm 類別使用的所有資源。Releases all resources used by the HashAlgorithm class.

(Inherited from HashAlgorithm)
ComputeHash(Byte[])

計算指定位元組陣列的雜湊值。Computes the hash value for the specified byte array.

(Inherited from HashAlgorithm)
ComputeHash(Byte[], Int32, Int32)

計算所指定位元組陣列中指定區域的雜湊值。Computes the hash value for the specified region of the specified byte array.

(Inherited from HashAlgorithm)
ComputeHash(Stream)

計算指定 Stream 物件的雜湊值。Computes the hash value for the specified Stream object.

(Inherited from HashAlgorithm)
ComputeHashAsync(Stream, CancellationToken) (Inherited from HashAlgorithm)
Create()

建立金鑰雜湊演算法之預設實作的執行個體。Creates an instance of the default implementation of a keyed hash algorithm.

Create(String)

建立金鑰雜湊演算法之指定實作的執行個體。Creates an instance of the specified implementation of a keyed hash algorithm.

Dispose()

釋放目前的 HashAlgorithm 類別執行個體所使用的所有資源。Releases all resources used by the current instance of the HashAlgorithm class.

(Inherited from HashAlgorithm)
Dispose(Boolean)

釋放 KeyedHashAlgorithm 使用的 Unmanaged 資源,並且選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the KeyedHashAlgorithm and optionally releases the managed resources.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

這個成員會覆寫 Finalize(),您可以在該主題中找到更完整的文件。This member overrides Finalize(), and more complete documentation might be available in that topic.

在記憶體回收 (GC) 回收 Object 前,允許 Object 嘗試釋放資源並執行其他清除作業。Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
HashCore(Byte[], Int32, Int32)

在衍生類別中覆寫時,將寫入物件的資料轉遞到用來計算雜湊的雜湊演算法。When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash.

(Inherited from HashAlgorithm)
HashCore(ReadOnlySpan<Byte>)

將寫入物件的資料路由傳送至雜湊演算法,以用來計算雜湊。Routes data written to the object into the hash algorithm for computing the hash.

(Inherited from HashAlgorithm)
HashFinal()

於衍生類型中覆寫時,在密碼編譯雜湊演算法處理最後一筆資料後,完成雜湊計算。When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic hash algorithm.

(Inherited from HashAlgorithm)
Initialize()

將雜湊演算法重設為其初始狀態。Resets the hash algorithm to its initial state.

(Inherited from HashAlgorithm)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

計算輸入位元組陣列中指定區域的雜湊值,並將指定的輸入位元組陣列區域複製到指定的輸出位元組陣列區域。Computes the hash value for the specified region of the input byte array and copies the specified region of the input byte array to the specified region of the output byte array.

(Inherited from HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

計算所指定位元組陣列中指定區域的雜湊值。Computes the hash value for the specified region of the specified byte array.

(Inherited from HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32)

嘗試計算指定位元組陣列的雜湊值。Attempts to compute the hash value for the specified byte array.

(Inherited from HashAlgorithm)
TryHashFinal(Span<Byte>, Int32)

在雜湊演算法處理最後一筆資料之後,嘗試完成雜湊計算。Attempts to finalize the hash computation after the last data is processed by the hash algorithm.

(Inherited from HashAlgorithm)

Explicit Interface Implementations

IDisposable.Dispose()

釋放 HashAlgorithm 使用的 Unmanaged 資源,並且選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources.

(Inherited from HashAlgorithm)

Applies to

See also