Condividi tramite


Integrità dei dati con codici hash

Un valore hash è un valore numerico di lunghezza fissa che identifica in modo univoco i dati. I valori hash rappresentano grandi quantità di dati come valori numerici più piccoli e vengono utilizzati con le firme digitali. È possibile firmare un valore hash in modo più efficiente rispetto alla firma di un valore più grande. I valori hash risultano utili anche per verificare l'integrità dei dati inviati su canali non protetti. Il valore hash dei dati ricevuti può essere confrontato con il valore hash di dati così come è stato inviato per determinare se i dati sono stati alterati.

In questo argomento viene descritto come generare e verificare codici hash utilizzando le classi nello spazio dei nomi System.Security.Cryptography.

Generazione di un hash

Le classi di hash gestite possono generare un hash in una matrice di byte o in un oggetto flusso gestito. Nell'esempio che segue viene utilizzato l'algoritmo hash SHA1 per creare un valore hash per una stringa. Nell'esempio viene utilizzata la classe UnicodeEncoding per convertire la stringa in una matrice di byte per cui viene generato un hash utilizzando la classe SHA1Managed. Il valore hash viene quindi visualizzato nella console.

Imports System
Imports System.Security.Cryptography
Imports System.Text

Module Program
    Sub Main()
        Dim HashValue() As Byte

        Dim MessageString As String = "This is the original message!"

        'Create a new instance of the UnicodeEncoding class to 
        'convert the string into an array of Unicode bytes.
        Dim UE As New UnicodeEncoding()

        'Convert the string into an array of bytes.
        Dim MessageBytes As Byte() = UE.GetBytes(MessageString)

        'Create a new instance of the SHA1Managed class to create 
        'the hash value.
        Dim SHhash As New SHA1Managed()

        'Create the hash value from the array of bytes.
        HashValue = SHhash.ComputeHash(MessageBytes)

        'Display the hash value to the console. 
        Dim b As Byte
        For Each b In HashValue
            Console.Write("{0} ", b)
        Next b
    End Sub
End Module
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Class1
{
    static void Main(string[] args)
    {
        byte[] HashValue;

        string MessageString = "This is the original message!";

        //Create a new instance of the UnicodeEncoding class to 
        //convert the string into an array of Unicode bytes.
        UnicodeEncoding UE = new UnicodeEncoding();

        //Convert the string into an array of bytes.
        byte[] MessageBytes = UE.GetBytes(MessageString);

        //Create a new instance of the SHA1Managed class to create 
        //the hash value.
        SHA1Managed SHhash = new SHA1Managed();

        //Create the hash value from the array of bytes.
        HashValue = SHhash.ComputeHash(MessageBytes);

        //Display the hash value to the console. 
        foreach (byte b in HashValue)
        {
            Console.Write("{0} ", b);
        }
    }
}

Nel codice precedente verrà visualizzata la seguente stringa sulla console:

59 4 248 102 77 97 142 201 210 12 224 93 25 41 100 197 213 134 130 135

Verifica di un hash

I dati possono essere confrontati a un valore hash per determinarne l'integrità. Generalmente nei dati viene generato un hash in un determinato momento e il valore hash viene in qualche modo protetto. Successivamente nei dati è possibile generare un hash ed eseguire il confronto con il valore protetto. Se i valori hash corrispondono, i dati non sono stati alterati. Se i valori non corrispondono, i dati sono danneggiati. Perché il sistema funzioni, è necessario che l'hash protetto sia crittografato o non rivelato a parti non affidabili.

Nell'esempio che segue viene confrontato il valore hash precedente di una stringa con un nuovo valore hash. Nell'esempio si scorre in ciclo ogni byte dei valori hash e viene effettuato un confronto.

Imports System
Imports System.Security.Cryptography
Imports System.Text

Module Module1
    Sub Main()
        'This hash value is produced from "This is the original message!" 
        'using SHA1Managed.  
        Dim SentHashValue As Byte() = {59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135}

        'This is the string that corresponds to the previous hash value.
        Dim MessageString As String = "This is the original message!"

        Dim CompareHashValue() As Byte

        'Create a new instance of the UnicodeEncoding class to 
        'convert the string into an array of Unicode bytes.
        Dim UE As New UnicodeEncoding()

        'Convert the string into an array of bytes.
        Dim MessageBytes As Byte() = UE.GetBytes(MessageString)

        'Create a new instance of the SHA1Managed class to create 
        'the hash value.
        Dim SHhash As New SHA1Managed()

        'Create the hash value from the array of bytes.
        CompareHashValue = SHhash.ComputeHash(MessageBytes)

        Dim Same As Boolean = True

        'Compare the values of the two byte arrays.
        Dim x As Integer
        For x = 0 To SentHashValue.Length - 1
            If SentHashValue(x) <> CompareHashValue(x) Then
                Same = False
            End If
        Next x
        'Display whether or not the hash values are the same.
        If Same Then
            Console.WriteLine("The hash codes match.")
        Else
            Console.WriteLine("The hash codes do not match.")
        End If
    End Sub
End Module
using System;
using System.Security.Cryptography;
using System.Text;

class Class1
{
    static void Main()
    {
        //This hash value is produced from "This is the original message!" 
        //using SHA1Managed.  
        byte[] SentHashValue = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };

        //This is the string that corresponds to the previous hash value.
        string MessageString = "This is the original message!";

        byte[] CompareHashValue;

        //Create a new instance of the UnicodeEncoding class to 
        //convert the string into an array of Unicode bytes.
        UnicodeEncoding UE = new UnicodeEncoding();

        //Convert the string into an array of bytes.
        byte[] MessageBytes = UE.GetBytes(MessageString);

        //Create a new instance of the SHA1Managed class to create 
        //the hash value.
        SHA1Managed SHhash = new SHA1Managed();

        //Create the hash value from the array of bytes.
        CompareHashValue = SHhash.ComputeHash(MessageBytes);

        bool Same = true;

        //Compare the values of the two byte arrays.
        for (int x = 0; x < SentHashValue.Length; x++)
        {
            if (SentHashValue[x] != CompareHashValue[x])
            {
                Same = false;
            }
        }
        //Display whether or not the hash values are the same.
        if (Same)
        {
            Console.WriteLine("The hash codes match.");
        }
        else
        {
            Console.WriteLine("The hash codes do not match.");
        }
    }
}

Se i due valori hash corrispondono, nel codice precedente verrà visualizzato quanto segue nella console:

The hash codes match.

Se non corrispondono, verrà visualizzato quanto segue:

The hash codes do not match.

Vedere anche

Concetti

Servizi di crittografia

Altre risorse

Attività di crittografia