Asegurar la integridad de los datos mediante códigos hash

Un valor hash es un valor numérico de longitud fija que solo identifica datos. Los valores hash representan grandes cantidades de datos como valores numéricos mucho menores, por lo que se usan con firmas digitales. Puede firmar un valor hash de forma más eficaz que un valor mayor. Los valores hash también son útiles para comprobar la integridad de datos enviados a través de canales no seguros. El valor hash de los datos recibidos puede compararse con el valor hash de los datos porque se envió para determinar si se alteraron los datos.

En este tema, se describe cómo generar y comprobar códigos hash mediante las clases en el espacio de nombres System.Security.Cryptography.

Generar un valor hash

Las clases hash pueden aplicar un valor hash a una matriz de bytes o a un objeto de secuencia. En el ejemplo siguiente, se utiliza el algoritmo hash SHA-256 para crear un valor hash para una cadena. El ejemplo utiliza Encoding.UTF8 para convertir la cadena en una matriz de bytes que aplica un valor hash mediante el uso de la clase SHA256. Posteriormente el valor hash se muestra en la consola.

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

Este código mostrará la cadena siguiente en la consola:

67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79

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. En caso contrario, 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.

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 también