Partilhar via


Garantindo a integridade dos dados com códigos hash

Um valor de hash é um valor numérico de um comprimento fixo que identifica exclusivamente os dados. Os valores de hash representam grandes quantidades de dados como valores numéricos muito menores, por isso são usados com assinaturas digitais. Você pode assinar um valor de hash de forma mais eficiente do que assinar o valor maior. Os valores de hash também são úteis para verificar a integridade dos dados enviados através de canais inseguros. O valor de hash dos dados recebidos pode ser comparado com o valor de hash dos dados à medida que foram enviados para determinar se os dados foram alterados.

Este tópico descreve como gerar e verificar códigos hash usando as classes no System.Security.Cryptography namespace.

Gerando um hash

As classes de hash podem hash de uma matriz de bytes ou um objeto de fluxo. O exemplo a seguir usa o algoritmo de hash SHA-256 para criar um valor de hash para uma cadeia de caracteres. O exemplo usa Encoding.UTF8 para converter a cadeia de caracteres em uma matriz de bytes que são hashed usando a SHA256 classe. O valor de hash é então exibido no console.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

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

//Convert the string into an array of bytes.
byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);

//Create the hash value from the array of bytes.
byte[] hashValue = SHA256.HashData(messageBytes);

//Display the hash value to the console.
Console.WriteLine(Convert.ToHexString(hashValue));
Imports System.Security.Cryptography
Imports System.Text

Module Program
    Sub Main()
        Dim messageString As String = "This is the original message!"

        'Convert the string into an array of bytes.
        Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString)

        'Create the hash value from the array of bytes.
        Dim hashValue As Byte() = SHA256.HashData(messageBytes)

        'Display the hash value to the console. 
        Console.WriteLine(Convert.ToHexString(hashValue))
    End Sub
End Module

Esse código exibirá a seguinte cadeia de caracteres no console:

67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79

Verificando um hash

Os dados podem ser comparados a um valor de hash para determinar sua integridade. Normalmente, os dados são colocados em hash em um determinado momento e o valor de hash é protegido de alguma forma. Mais tarde, os dados podem ser colocados em hash novamente e comparados com o valor protegido. Se os valores de hash corresponderem, os dados não foram alterados. Se os valores não corresponderem, os dados foram corrompidos. Para que esse sistema funcione, o hash protegido deve ser criptografado ou mantido em segredo de todas as partes não confiáveis.

O exemplo a seguir compara o valor de hash anterior de uma cadeia de caracteres com um novo valor de hash.

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

//This hash value is produced from "This is the original message!"
//using SHA256.
byte[] sentHashValue = Convert.FromHexString("67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79");

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

//Convert the string into an array of bytes.
byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);

//Create the hash value from the array of bytes.
byte[] compareHashValue = SHA256.HashData(messageBytes);

//Compare the values of the two byte arrays.
bool same = sentHashValue.SequenceEqual(compareHashValue);

//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.");
}
Imports System.Linq
Imports System.Security.Cryptography
Imports System.Text

Module Module1
    Sub Main()
        'This hash value is produced from "This is the original message!" 
        'using SHA256.  
        Dim sentHashValue As Byte() = Convert.FromHexString("67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79")

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

        'Convert the string into an array of bytes.
        Dim messageBytes As Byte() = Encoding.UTF8.GetBytes(messageString)

        'Create the hash value from the array of bytes.
        Dim compareHashValue As Byte() = SHA256.HashData(messageBytes)

        'Compare the values of the two byte arrays.
        Dim same As Boolean = sentHashValue.SequenceEqual(compareHashValue)

        '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

Consulte também