KeyedHashAlgorithm KeyedHashAlgorithm KeyedHashAlgorithm KeyedHashAlgorithm Class

Definizione

Rappresenta la classe astratta dalla quale devono derivare tutte le implementazioni degli algoritmi hash con chiave.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
Ereditarietà
KeyedHashAlgorithmKeyedHashAlgorithmKeyedHashAlgorithmKeyedHashAlgorithm
Derivato
Attributi

Esempi

Nell'esempio di codice riportato di seguito viene illustrato come derivare dalla KeyedHashAlgorithm classe.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

Commenti

Le funzioni hash mappano stringhe binarie di lunghezza arbitraria a stringhe binarie di piccole dimensioni a lunghezza fissa.Hash functions map binary strings of an arbitrary length to small binary strings of a fixed length. Una funzione hash crittografica ha la proprietà che è inutilizzabile dal punto di vista del calcolo per trovare due input distinti che consentono di eseguire l'hashing allo stesso valore.A cryptographic hash function has the property that it is computationally infeasible to find two distinct inputs that hash to the same value. Le piccole modifiche apportate ai dati comportano modifiche imprevedibili e di grandi dimensioni nell'hash.Small changes to the data result in large, unpredictable changes in the hash.

Un algoritmo hash con chiave è una funzione hash unidirezionale dipendente dalla chiave utilizzata come codice di autenticazione del messaggio.A keyed hash algorithm is a key-dependent, one-way hash function used as a message authentication code. Solo un utente che conosce la chiave può verificare l'hash.Only someone who knows the key can verify the hash. Gli algoritmi hash con chiave forniscono autenticità senza riservatezza.Keyed hash algorithms provide authenticity without secrecy.

Le funzioni hash vengono comunemente usate con le firme digitali e per l'integrità dei dati.Hash functions are commonly used with digital signatures and for data integrity. La HMACSHA1 classe è un esempio di algoritmo hash con chiave.The HMACSHA1 class is an example of a keyed hash algorithm.

A causa di problemi di collisione con SHA1, Microsoft consiglia un modello di sicurezza basato su SHA256 o superiore.Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better.

Costruttori

KeyedHashAlgorithm() KeyedHashAlgorithm() KeyedHashAlgorithm() KeyedHashAlgorithm()

Inizializza una nuova istanza della classe KeyedHashAlgorithm.Initializes a new instance of the KeyedHashAlgorithm class.

Campi

HashSizeValue HashSizeValue HashSizeValue HashSizeValue

Rappresenta la dimensione in bit del codice hash calcolato.Represents the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
HashValue HashValue HashValue HashValue

Rappresenta il valore del codice hash calcolato.Represents the value of the computed hash code.

(Inherited from HashAlgorithm)
KeyValue KeyValue KeyValue KeyValue

Chiave da utilizzare nell'algoritmo hash.The key to use in the hash algorithm.

State State State State

Rappresenta lo stato del calcolo hash.Represents the state of the hash computation.

(Inherited from HashAlgorithm)

Proprietà

CanReuseTransform CanReuseTransform CanReuseTransform CanReuseTransform

Ottiene un valore che indica se è possibile riutilizzare la trasformazione corrente.Gets a value indicating whether the current transform can be reused.

(Inherited from HashAlgorithm)
CanTransformMultipleBlocks CanTransformMultipleBlocks CanTransformMultipleBlocks CanTransformMultipleBlocks

Quando ne viene eseguito l'override in una classe derivata, ottiene un valore che indica se è possibile trasformare più blocchi.When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed.

(Inherited from HashAlgorithm)
Hash Hash Hash Hash

Ottiene il valore del codice hash calcolato.Gets the value of the computed hash code.

(Inherited from HashAlgorithm)
HashSize HashSize HashSize HashSize

Ottiene la dimensione in bit del codice hash calcolato.Gets the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
InputBlockSize InputBlockSize InputBlockSize InputBlockSize

Quando è sottoposta a override in una classe derivata, consente di ottenere la dimensione del blocco di input.When overridden in a derived class, gets the input block size.

(Inherited from HashAlgorithm)
Key Key Key Key

Ottiene o imposta la chiave da utilizzare nell'algoritmo hash.Gets or sets the key to use in the hash algorithm.

OutputBlockSize OutputBlockSize OutputBlockSize OutputBlockSize

Quando è sottoposta a override in una classe derivata, consente di ottenere la dimensione del blocco di output.When overridden in a derived class, gets the output block size.

(Inherited from HashAlgorithm)

Metodi

Clear() Clear() Clear() Clear()

Rilascia tutte le risorse usate dalla classe HashAlgorithm.Releases all resources used by the HashAlgorithm class.

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

Consente di calcolare il valore hash della matrice di byte specificata.Computes the hash value for the specified byte array.

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

Consente di calcolare il valore hash dell'area specifica della matrice di byte specificata.Computes the hash value for the specified region of the specified byte array.

(Inherited from HashAlgorithm)
ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream)

Calcola il valore hash per l'oggetto Stream specificato.Computes the hash value for the specified Stream object.

(Inherited from HashAlgorithm)
Create() Create() Create() Create()

Crea un'istanza dell'implementazione predefinita di un algoritmo hash con chiave.Creates an instance of the default implementation of a keyed hash algorithm.

Create(String) Create(String) Create(String) Create(String)

Consente di creare un'istanza dell'implementazione specificata di un algoritmo hash con chiave.Creates an instance of the specified implementation of a keyed hash algorithm.

Dispose() Dispose() Dispose() Dispose()

Rilascia tutte le risorse usate dall'istanza corrente della classe HashAlgorithm.Releases all resources used by the current instance of the HashAlgorithm class.

(Inherited from HashAlgorithm)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Rilascia le risorse non gestite usate da KeyedHashAlgorithm e, facoltativamente, le risorse gestite.Releases the unmanaged resources used by the KeyedHashAlgorithm and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Questo membro esegue l'override di Finalize(). L'argomento corrispondente può contenere documentazione più completa.This member overrides Finalize(), and more complete documentation might be available in that topic.

Consente a un oggetto Object di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che l'oggetto Object stesso venga recuperato dalla procedura di Garbage Collection.Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Funge da funzione hash predefinita.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

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

Quando è sottoposto a override in una classe derivata, consente di indirizzare i dati scritti nell'oggetto verso l'algoritmo hash per il calcolo dell'hash.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>) HashCore(ReadOnlySpan<Byte>) HashCore(ReadOnlySpan<Byte>) HashCore(ReadOnlySpan<Byte>) Inherited from HashAlgorithm
HashFinal() HashFinal() HashFinal() HashFinal()

Quando è sottoposto a override in una classe derivata, consente di finalizzare il calcolo hash una volta che gli ultimi dati sono stati elaborati dall'oggetto flusso crittografato.When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic stream object.

(Inherited from HashAlgorithm)
Initialize() Initialize() Initialize() Initialize()

Inizializza un'implementazione della classe HashAlgorithm.Initializes an implementation of the HashAlgorithm class.

(Inherited from HashAlgorithm)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object.

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

Consente di calcolare il valore hash dell'area specifica della matrice di byte di input e di copiare una determinata area della matrice di byte di input nell'area specifica della matrice di byte di output.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) TransformFinalBlock(Byte[], Int32, Int32) TransformFinalBlock(Byte[], Int32, Int32) TransformFinalBlock(Byte[], Int32, Int32)

Consente di calcolare il valore hash dell'area specifica della matrice di byte specificata.Computes the hash value for the specified region of the specified byte array.

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

Implementazioni dell'interfaccia esplicita

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Rilascia le risorse non gestite usate da HashAlgorithm e, facoltativamente, le risorse gestite.Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources.

(Inherited from HashAlgorithm)

Si applica a

Vedi anche