KeyedHashAlgorithm Clase

Definición

Representa la clase abstracta de la que deben derivarse todas las implementaciones de algoritmos hash en clave.

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
Herencia
KeyedHashAlgorithm
Derivado
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo derivar de la KeyedHashAlgorithm clase .

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

Comentarios

Las funciones hash asignan cadenas binarias de una longitud arbitraria a cadenas binarias pequeñas de una longitud fija. Una función hash criptográfica tiene la propiedad que es computacionalmente inviable para buscar dos entradas distintas que hash en el mismo valor. Los pequeños cambios en los datos dan como resultado cambios grandes e imprevisibles en el hash.

Un algoritmo hash con clave es una función hash unidireccional dependiente de la clave que se usa como código de autenticación de mensajes. Solo alguien que conoce la clave puede comprobar el hash. Los algoritmos hash con clave proporcionan autenticidad sin secreto.

Las funciones hash se usan normalmente con firmas digitales y en tareas de integridad de datos. La HMACSHA1 clase es un ejemplo de un algoritmo hash con clave.

Debido a problemas de colisión con SHA1, Microsoft recomienda un modelo de seguridad basado en SHA256 o mejor.

Constructores

KeyedHashAlgorithm()

Inicializa una nueva instancia de la clase KeyedHashAlgorithm.

Campos

HashSizeValue

Representa el tamaño en bits del código hash calculado.

(Heredado de HashAlgorithm)
HashValue

Representa el valor del código hash calculado.

(Heredado de HashAlgorithm)
KeyValue

Clave que se va a usar en el algoritmo hash.

State

Representa el estado del cálculo del valor hash.

(Heredado de HashAlgorithm)

Propiedades

CanReuseTransform

Obtiene un valor que indica si la transformación actual puede volver a usarse.

(Heredado de HashAlgorithm)
CanTransformMultipleBlocks

Cuando se invalida en una clase derivada, obtiene un valor que indica si se pueden transformar varios bloques.

(Heredado de HashAlgorithm)
Hash

Obtiene el valor del código hash calculado.

(Heredado de HashAlgorithm)
HashSize

Obtiene el tamaño en bits del código hash calculado.

(Heredado de HashAlgorithm)
InputBlockSize

Cuando se invalida en una clase derivada, obtiene el tamaño del bloque de entrada.

(Heredado de HashAlgorithm)
Key

Obtiene o establece la clave que se va a usar en el algoritmo hash.

OutputBlockSize

Cuando se invalida en una clase derivada, obtiene el tamaño del bloque de salida.

(Heredado de HashAlgorithm)

Métodos

Clear()

Libera todos los recursos que utiliza la clase HashAlgorithm.

(Heredado de HashAlgorithm)
ComputeHash(Byte[])

Calcula el valor hash para la matriz de bytes especificada.

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

Calcula el valor hash para la región especificada de la matriz de bytes indicada.

(Heredado de HashAlgorithm)
ComputeHash(Stream)

Calcula el valor hash del objeto Stream especificado.

(Heredado de HashAlgorithm)
ComputeHashAsync(Stream, CancellationToken)

Calcula de manera asincrónica el valor hash del objeto Stream especificado.

(Heredado de HashAlgorithm)
Create()
Obsoleto.
Obsoleto.

Crea una instancia de la implementación predeterminada de un algoritmo hash en clave.

Create(String)

Crea una instancia de la implementación especificada de un algoritmo hash en clave.

Dispose()

Libera todos los recursos usados por la instancia actual de la clase HashAlgorithm.

(Heredado de HashAlgorithm)
Dispose(Boolean)

Libera los recursos no administrados que usa KeyedHashAlgorithm y, de forma opcional, libera los recursos administrados.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
Finalize()

Este miembro reemplaza a Finalize(); puede haber documentación más completa en ese tema.

Permite que un objeto Object intente liberar recursos y realizar otras operaciones de limpieza antes de que el objeto Object sea reclamado por la recolección de elementos no utilizados.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

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

Cuando se invalida en una clase derivada, enruta los datos escritos en el objeto al algoritmo hash para el cálculo del valor hash.

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

Envía los datos escritos en el objeto al algoritmo hash para el cálculo del valor hash.

(Heredado de HashAlgorithm)
HashFinal()

Cuando se invalida en una clase derivada, finaliza el cálculo de hash una vez que el algoritmo hash criptográfico termina de procesar los últimos datos.

(Heredado de HashAlgorithm)
Initialize()

Restablece el algoritmo hash a su estado inicial.

(Heredado de HashAlgorithm)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

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

Calcula el valor hash para la región especificada de la matriz de bytes de entrada y copia la región especificada de la matriz de bytes de entrada resultante en la región indicada de la matriz de bytes de salida.

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

Calcula el valor hash para la región especificada de la matriz de bytes indicada.

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

Intenta calcular el valor de hash para la matriz de bytes especificada.

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

Intenta finalizar el cálculo de hash una vez que el algoritmo hash procesa los últimos datos.

(Heredado de HashAlgorithm)

Implementaciones de interfaz explícitas

IDisposable.Dispose()

Libera los recursos no administrados que usa HashAlgorithm y, de forma opcional, libera los recursos administrados.

(Heredado de HashAlgorithm)

Se aplica a

Consulte también