해시 코드를 사용하여 데이터 무결성 보장

해시 값을 데이터를 고유하게 식별하는 고정 길이 숫자 값입니다. 해시 값은 대용량 데이터를 훨씬 더 작은 숫자 값으로 나타내므로 디지털 서명과 함께 사용됩니다. 해시 값에 서명하는 것이 더 큰 값에 서명하는 것보다 더 효율적입니다. 해시 값은 안전하지 않은 채널을 통해 전송된 데이터의 무결성을 확인하는 데도 유용합니다. 수신된 데이터의 해시 값을 전송된 데이터의 해시 값과 비교하여 데이터가 변경되었는지 확인할 수 있습니다.

이 항목에서는 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

참고 항목