Обеспечение целостности данных с помощью хэш-кодов

Хэш-код является численным значением фиксированной длины, которое однозначно идентифицирует данные. Хэш-коды представляют большие объемы данных в виде намного меньших по объему числовых значений, поэтому они используются с цифровыми подписями. Хэш-код можно подписать более эффективно, чем значение большего размера. Хэш-коды также могут использоваться для проверки целостности данных, пересылаемых по незащищенным каналам. Хэш-код полученных данных можно сравнить с хэш-кодом этих же данных, вычисленным перед их передачей, и на основании этого определить, подвергались ли данные изменениям.

В этом разделе описываются способы создания и проверки хэш-кодов с помощью классов пространства имен System.Security.Cryptography.

Создание хэша

Хэш-классы могут хэш-классы либо массив байтов, либо объект потока. В следующем примере используется хэш-алгоритм SHA-256 для создания хэш-значения для строки. В примере используется Encoding.UTF8 для преобразования строки в массив байтов, хэшированных с помощью SHA256 класса. После этого хэш-код выводится на консоль.

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

Этот код выводит на консоль следующую строку:

67A1790DCA55B8803AD024EE28F616A284DF5DD7B8BA5F68B4B252A5E925AF79

Проверка хэша

Проверку целостности данных можно производить на основании сравнения их с хэш-кодом. Обычно данные хэшируются в некоторый момент времени, а затем их хэш-код защищается каким-либо образом. Позже можно снова хэшировать эти данные и результат сравнивать с защищенным хэш-кодом. Если хэш-коды совпадают, значит, данные не изменялись. Несовпадение хэш-кодов свидетельствует о том, что данные были повреждены. Чтобы такой механизм был работоспособен, защищенный хэш должен быть зашифрован или являться недоступным для всех лиц, не имеющих достаточного доверия.

В примере ниже ранее полученный хэш-код строки сравнивается с ее новым хэш-кодом.

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

См. также