Partilhar via


Garantindo a integridade dos dados com códigos de Hash

Um valor de hash é um valor numérico de comprimento fixo que identifica com exclusividade os dados. Os valores de hash representam grandes quantidades de dados como valores numéricos de muito menores, para que elas são usadas com assinaturas digitais. Você pode assinar um valor de hash de forma mais eficiente o maior valor de assinatura. Os valores de hash também são úteis para a verificação da integridade dos dados enviados através de canais inseguros. O valor de hash de dados recebidos pode ser comparado ao valor de hash de dados, como ele foi enviado para determinar se os dados foi alterados.

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

Gerando um Hash.

As classes de hash gerenciado podem hash de uma matriz de bytes ou em um objeto gerenciado stream. O exemplo a seguir usa o algoritmo de hash SHA1 para criar um valor de hash para uma seqüência de caracteres. O exemplo usa o UnicodeEncoding classe para converter a seqüência de caracteres em uma matriz de bytes que estão em hash usando o SHA1Managed classe. O valor de hash é exibido no 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);
        }
    }
}

Este código irá exibir a seguinte seqüência ao console:

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

Verificando um Hash.

Dados podem ser comparados com um valor de hash para determinar sua integridade. Em geral, os dados são misturados em determinado momento e o valor de hash é protegido de alguma maneira. Posteriormente, os dados podem ser misturados novamente e comparados ao valor protegido. Se os valores de hash coincidirem, os dados não foram alterados. Se os valores não coincidirem, os dados foram corrompidos. Para esse sistema funcionar, 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 seqüência de caracteres para um novo valor de hash. Este exemplo percorre cada byte dos valores de hash e faz uma comparação.

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 os dois valores de hash coincidirem, esse código exibe o seguinte no console:

The hash codes match.

Se eles não corresponderem, o código exibe o seguinte:

The hash codes do not match.

Consulte também

Conceitos

Serviços de criptografia

Outros recursos

Tarefas de criptografia