KeyedHashAlgorithm 类

定义

显示所有加密哈希算法实现均必须从中派生的抽象类。Represents the abstract class from which all implementations of keyed hash algorithms must derive.

public ref class KeyedHashAlgorithm abstract : 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
继承
KeyedHashAlgorithm
派生
属性

示例

下面的代码示例演示如何从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

注解

哈希函数将任意长度的二进制字符串映射为固定长度的小型二进制字符串。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.

构造函数

KeyedHashAlgorithm()

初始化 KeyedHashAlgorithm 类的新实例。Initializes a new instance of the KeyedHashAlgorithm class.

字段

HashSizeValue

表示计算所得的哈希代码的大小(以位为单位)。Represents the size, in bits, of the computed hash code.

(继承自 HashAlgorithm)
HashValue

表示计算所得的哈希代码的值。Represents the value of the computed hash code.

(继承自 HashAlgorithm)
KeyValue

用于哈希算法的密钥。The key to use in the hash algorithm.

State

表示哈希计算的状态。Represents the state of the hash computation.

(继承自 HashAlgorithm)

属性

CanReuseTransform

获取一个值,该值指示是否可重复使用当前转换。Gets a value indicating whether the current transform can be reused.

(继承自 HashAlgorithm)
CanTransformMultipleBlocks

当在派生类中重写时,获取一个值,该值指示是否可以转换多个块。When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed.

(继承自 HashAlgorithm)
Hash

获取计算所得的哈希代码的值。Gets the value of the computed hash code.

(继承自 HashAlgorithm)
HashSize

获取计算所得的哈希代码的大小(以位为单位)。Gets the size, in bits, of the computed hash code.

(继承自 HashAlgorithm)
InputBlockSize

当在派生类中重写时,获取输入块的大小。When overridden in a derived class, gets the input block size.

(继承自 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.

(继承自 HashAlgorithm)

方法

Clear()

释放 HashAlgorithm 类使用的所有资源。Releases all resources used by the HashAlgorithm class.

(继承自 HashAlgorithm)
ComputeHash(Byte[])

计算指定字节数组的哈希值。Computes the hash value for the specified byte array.

(继承自 HashAlgorithm)
ComputeHash(Byte[], Int32, Int32)

计算指定字节数组的指定区域的哈希值。Computes the hash value for the specified region of the specified byte array.

(继承自 HashAlgorithm)
ComputeHash(Stream)

计算指定 Stream 对象的哈希值。Computes the hash value for the specified Stream object.

(继承自 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.

(继承自 HashAlgorithm)
Dispose(Boolean)

释放由 KeyedHashAlgorithm 占用的非托管资源,还可以另外再释放托管资源。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.

(继承自 Object)
Finalize()

此成员替代 Finalize() 且该主题可能包括更完整的文档。This member overrides Finalize(), and more complete documentation might be available in that topic.

允许 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.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 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.

(继承自 HashAlgorithm)
HashCore(ReadOnlySpan<Byte>) (继承自 HashAlgorithm)
HashFinal()

当在派生类中重写时,在加密流对象处理完最后的数据后完成哈希计算。When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic stream object.

(继承自 HashAlgorithm)
Initialize()

初始化 HashAlgorithm 类的实现。Initializes an implementation of the HashAlgorithm class.

(继承自 HashAlgorithm)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 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.

(继承自 HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

计算指定字节数组的指定区域的哈希值。Computes the hash value for the specified region of the specified byte array.

(继承自 HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) (继承自 HashAlgorithm)
TryHashFinal(Span<Byte>, Int32) (继承自 HashAlgorithm)

显式界面实现

IDisposable.Dispose()

释放由 HashAlgorithm 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources.

(继承自 HashAlgorithm)

适用于

另请参阅