KeyedHashAlgorithm Classe

Definição

Representa a classe base abstrata da qual todas as implementações de algoritmo de hash inseridas devem derivar.

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
[<System.Runtime.InteropServices.ComVisible(true)>]
type KeyedHashAlgorithm = class
    inherit HashAlgorithm
Public MustInherit Class KeyedHashAlgorithm
Inherits HashAlgorithm
Herança
KeyedHashAlgorithm
Derivado
Atributos

Exemplos

O exemplo de código a seguir demonstra como derivar da KeyedHashAlgorithm classe.

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

Comentários

As funções de hash mapeiam cadeias de caracteres binárias de um comprimento arbitrário para cadeias de caracteres binárias pequenas de um comprimento fixo. Uma função de hash criptográfica tem a propriedade de que é computacionalmente inviável encontrar duas entradas distintas que têm o mesmo valor. Pequenas alterações nos dados resultam em alterações grandes e imprevisíveis no hash.

Um algoritmo de hash chave é uma função hash unidirecional dependente de chave usada como um código de autenticação de mensagem. Somente alguém que conhece a chave pode verificar o hash. Algoritmos de hash chave fornecem autenticidade sem sigilo.

As funções de hash são utilizadas com assinaturas digitais e integridade dos dados. A HMACSHA1 classe é um exemplo de um algoritmo de hash chaveado.

Devido a problemas de colisão com o SHA1, a Microsoft recomenda um modelo de segurança baseado em SHA256 ou melhor.

Construtores

KeyedHashAlgorithm()

Inicializa uma nova instância da classe KeyedHashAlgorithm.

Campos

HashSizeValue

Representa o tamanho, em bits, do código hash calculado.

(Herdado de HashAlgorithm)
HashValue

Representa o valor do código hash computado.

(Herdado de HashAlgorithm)
KeyValue

A chave a ser usada no algoritmo de hash.

State

Representa o estado do cálculo de hash.

(Herdado de HashAlgorithm)

Propriedades

CanReuseTransform

Obtém um valor que indica se a transformação atual pode ser reutilizada.

(Herdado de HashAlgorithm)
CanTransformMultipleBlocks

Quando substituído em uma classe derivada, obtém um valor que indica se vários blocos podem ser transformados.

(Herdado de HashAlgorithm)
Hash

Obtém o valor do código hash computado.

(Herdado de HashAlgorithm)
HashSize

Obtém o tamanho, em bits, do código hash computado.

(Herdado de HashAlgorithm)
InputBlockSize

Quando substituído em uma classe derivada, obtém o tamanho do bloco de entrada.

(Herdado de HashAlgorithm)
Key

Obtém ou define a chave a ser usada no algoritmo de hash.

OutputBlockSize

Quando substituído em uma classe derivada, obtém o tamanho do bloco de saída.

(Herdado de HashAlgorithm)

Métodos

Clear()

Libera todos os recursos usados pela classe HashAlgorithm.

(Herdado de HashAlgorithm)
ComputeHash(Byte[])

Calcula o valor do hash da matriz de bytes especificada.

(Herdado de HashAlgorithm)
ComputeHash(Byte[], Int32, Int32)

Calcula o valor de hash para a região especificada da matriz de bytes especificada.

(Herdado de HashAlgorithm)
ComputeHash(Stream)

Calcula o valor do hash do objeto Stream especificado.

(Herdado de HashAlgorithm)
ComputeHashAsync(Stream, CancellationToken)

Calcula assincronamente o valor do hash do objeto Stream especificado.

(Herdado de HashAlgorithm)
Create()
Obsoleto.
Obsoleto.

Cria uma instância da implementação padrão de um algoritmo de hash com chave.

Create(String)

Cria uma instância da implementação especificada de um algoritmo de hash com chave.

Dispose()

Libera todos os recursos usados pela instância atual da classe HashAlgorithm.

(Herdado de HashAlgorithm)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo KeyedHashAlgorithm e opcionalmente libera os recursos gerenciados.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Este membro substitui Finalize(), e pode haver uma documentação mais completa disponível nesse tópico.

Permite que um Object tente liberar recursos e executar outras operações de limpeza antes que Object seja recuperado pela coleta de lixo.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
HashCore(Byte[], Int32, Int32)

Quando substituído em uma classe derivada, roteia os dados gravados no objeto para o algoritmo de hash para computar o hash.

(Herdado de HashAlgorithm)
HashCore(ReadOnlySpan<Byte>)

Roteia os dados gravados no objeto para o algoritmo de hash para cálculo do hash.

(Herdado de HashAlgorithm)
HashFinal()

Quando substituído em uma classe derivada, finaliza o cálculo de hash depois que os últimos dados são processados pelo algoritmo de hash de criptografia.

(Herdado de HashAlgorithm)
Initialize()

Redefine o algoritmo de hash para o estado inicial.

(Herdado de HashAlgorithm)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

Calcula o valor de hash para a região especificada da matriz de bytes de entrada e copia a região especificada da matriz de bytes de entrada para a região especificada da matriz de bytes de saída.

(Herdado de HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

Calcula o valor de hash para a região especificada da matriz de bytes especificada.

(Herdado de HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32)

Tenta calcular o valor de hash para a matriz de bytes especificada.

(Herdado de HashAlgorithm)
TryHashFinal(Span<Byte>, Int32)

Tenta finalizar o cálculo de hash depois que os últimos dados são processados pelo algoritmo de hash.

(Herdado de HashAlgorithm)

Implantações explícitas de interface

IDisposable.Dispose()

Libera os recursos não gerenciados usados pelo HashAlgorithm e opcionalmente libera os recursos gerenciados.

(Herdado de HashAlgorithm)

Aplica-se a

Confira também