Compartir a través de


Comprobar un valor hash

Los datos pueden compararse con un valor hash para determinar su integridad. Normalmente, el valor hash de los datos se calcula en un momento determinado y se protege de algún modo. Posteriormente, se puede calcular de nuevo el valor hash de los datos y compararse con el valor protegido. Si coinciden los dos valores hash, los datos no se han alterado. No obstante, si no coinciden, los datos se han dañado. Para que este sistema funcione, el valor hash protegido debe cifrarse o mantenerse fuera del alcance de quienes no sean de confianza.

En el ejemplo siguiente se compara el valor hash anterior de una cadena con un valor hash nuevo. En este ejemplo se recorre cada byte de los valores hash y se realiza una comparación.

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.");
      }
   }
}

Si los dos valores hash coinciden, este código mostrará lo siguiente en la consola:

The hash codes match.

No obstante, si no coinciden, el código mostrará lo siguiente:

The hash codes do not match.

Vea también

Conceptos

Generar un valor hash
Asegurar la integridad de los datos mediante códigos hash

Otros recursos

Tareas criptográficas
Servicios criptográficos