KeyedHashAlgorithm Classe

Definizione

Rappresenta la classe astratta da cui devono derivare tutte le implementazioni di algoritmi hash con chiave.

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
Ereditarietà
KeyedHashAlgorithm
Derivato
Attributi

Esempio

Nell'esempio di codice seguente viene illustrato come derivare dalla 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)
        {
            hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
            bHashing = true;
        }
        hash1.TransformBlock(rgb, ib, cb, rgb, ib);
    }

    protected override byte[] HashFinal()
    {
        if (!bHashing)
        {
            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

Commenti

Le funzioni hash eseguono il mapping di stringhe binarie di lunghezza arbitraria a stringhe binarie di lunghezza fissa. Una funzione hash crittografica ha la proprietà che è infeasible a livello di calcolo per trovare due input distinti che eseguino lo stesso valore. Piccole modifiche apportate ai dati comportano modifiche imprevedibili e di grandi dimensioni nell'hash.

Un algoritmo hash con chiave è una funzione hash unidirezionale dipendente dalla chiave usata come codice di autenticazione del messaggio. Solo un utente che conosce la chiave può verificare l'hash. Gli algoritmi hash con chiave forniscono l'autenticità senza segretezza.

Le funzioni hash vengono comunemente usate con firme digitali e per l'integrità dei dati. La HMACSHA1 classe è un esempio di algoritmo hash con chiave.

A causa di problemi di collisione con SHA-1, Microsoft consiglia un modello di sicurezza basato su SHA-256 o superiore.

Costruttori

Nome Descrizione
KeyedHashAlgorithm()

Inizializza una nuova istanza della classe KeyedHashAlgorithm.

Campi

Nome Descrizione
HashSizeValue

Rappresenta le dimensioni, in bit, del codice hash calcolato.

(Ereditato da HashAlgorithm)
HashValue

Rappresenta il valore del codice hash calcolato.

(Ereditato da HashAlgorithm)
KeyValue

Chiave da usare nell'algoritmo hash.

State

Rappresenta lo stato del calcolo hash.

(Ereditato da HashAlgorithm)

Proprietà

Nome Descrizione
CanReuseTransform

Ottiene un valore che indica se la trasformazione corrente può essere riutilizzata.

(Ereditato da HashAlgorithm)
CanTransformMultipleBlocks

In caso di override in una classe derivata, ottiene un valore che indica se è possibile trasformare più blocchi.

(Ereditato da HashAlgorithm)
Hash

Ottiene il valore del codice hash calcolato.

(Ereditato da HashAlgorithm)
HashSize

Ottiene le dimensioni, in bit, del codice hash calcolato.

(Ereditato da HashAlgorithm)
InputBlockSize

In caso di override in una classe derivata, ottiene le dimensioni del blocco di input.

(Ereditato da HashAlgorithm)
Key

Ottiene o imposta la chiave da utilizzare nell'algoritmo hash.

OutputBlockSize

Quando sottoposto a override in una classe derivata, ottiene le dimensioni del blocco di output.

(Ereditato da HashAlgorithm)

Metodi

Nome Descrizione
Clear()

Rilascia tutte le risorse usate dalla HashAlgorithm classe .

(Ereditato da HashAlgorithm)
ComputeHash(Byte[], Int32, Int32)

Calcola il valore hash per l'area specificata della matrice di byte specificata.

(Ereditato da HashAlgorithm)
ComputeHash(Byte[])

Calcola il valore hash per la matrice di byte specificata.

(Ereditato da HashAlgorithm)
ComputeHash(Stream)

Calcola il valore hash per l'oggetto specificato Stream .

(Ereditato da HashAlgorithm)
Create()

Crea un'istanza dell'implementazione predefinita di un algoritmo hash con chiave.

Create(String)

Crea un'istanza dell'implementazione specificata di un algoritmo hash con chiave.

Dispose()

Rilascia tutte le risorse usate dall'istanza corrente della HashAlgorithm classe .

(Ereditato da HashAlgorithm)
Dispose(Boolean)

Rilascia le risorse non gestite usate da KeyedHashAlgorithm e, facoltativamente, rilascia le risorse gestite.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Finalize()

Questo membro esegue l'override Finalize()di e una documentazione più completa potrebbe essere disponibile in tale argomento.

Consente di tentare Object di liberare risorse ed eseguire altre operazioni di pulizia prima che venga Object recuperato da Garbage Collection.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
HashCore(Byte[], Int32, Int32)

In caso di override in una classe derivata, instrada i dati scritti nell'oggetto nell'algoritmo hash per calcolare l'hash.

(Ereditato da HashAlgorithm)
HashCore(ReadOnlySpan<Byte>)

Indirizza i dati scritti nell'oggetto nell'algoritmo hash per calcolare l'hash.

(Ereditato da HashAlgorithm)
HashFinal()

Quando sottoposto a override in una classe derivata, finalizza il calcolo hash dopo l'elaborazione degli ultimi dati dall'algoritmo hash crittografico.

(Ereditato da HashAlgorithm)
Initialize()

Reimposta lo stato iniziale dell'algoritmo hash.

(Ereditato da HashAlgorithm)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

Calcola il valore hash per l'area specificata della matrice di byte di input e copia l'area specificata della matrice di byte di input nell'area specificata della matrice di byte di output.

(Ereditato da HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32)

Calcola il valore hash per l'area specificata della matrice di byte specificata.

(Ereditato da HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32)

Tenta di calcolare il valore hash per la matrice di byte specificata.

(Ereditato da HashAlgorithm)
TryHashFinal(Span<Byte>, Int32)

Tenta di finalizzare il calcolo hash dopo l'elaborazione degli ultimi dati dall'algoritmo hash.

(Ereditato da HashAlgorithm)

Implementazioni dell'interfaccia esplicita

Nome Descrizione
IDisposable.Dispose()

Rilascia le risorse non gestite usate da HashAlgorithm e, facoltativamente, rilascia le risorse gestite.

(Ereditato da HashAlgorithm)

Si applica a

Vedi anche