다음을 통해 공유


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

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

이 항목에서는 System.Security.Cryptography 네임스페이스의 클래스를 사용하여 해시 코드를 생성하고 확인하는 방법에 대해 설명합니다.

해시 생성

관리되는 해시 클래스에서는 바이트 배열이나 관리되는 스트림 개체를 해시할 수 있습니다. 다음 예제에서는 SHA1 해시 알고리즘을 사용하여 문자열에 대한 해시 값을 만듭니다. 다음 예제에서는 SHA1Managed 클래스를 사용하여 문자열을 해시된 바이트 배열로 변환하기 위해 UnicodeEncoding 클래스를 사용합니다. 그런 다음에는 해당 해시 값이 콘솔에 표시됩니다.

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

이 코드에서는 다음 문자열을 콘솔에 표시합니다.

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

해시 확인

데이터를 해시 값과 비교하여 데이터 무결성을 확인할 수 있습니다. 일반적으로 데이터는 특정 시기에 해시되며 해시 값은 몇 가지 방법으로 보호됩니다. 나중에 데이터를 다시 해시하여 보호된 값과 비교할 수 있습니다. 해시 값이 일치하면 데이터가 변경되지 않은 것입니다. 해시 값이 일치하지 않으면 데이터가 손상된 것입니다. 이 시스템이 올바르게 작동하려면 보호된 해시를 암호화하거나 신뢰할 수 없는 사람은 이 해시를 알 수 없도록 해야 합니다.

다음 예제에서는 앞의 문자열에 대한 해시 값을 새 해시 값과 비교합니다. 이 예제에서는 해시 값의 각 바이트를 전체 반복하여 비교를 수행합니다.

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

두 해시 값이 일치하면 이 코드에서는 콘솔에 다음 메시지를 표시합니다.

The hash codes match.

두 해시 값이 일치하지 않으면 이 코드에서는 다음 메시지를 표시합니다.

The hash codes do not match.

참고 항목

개념

암호화 서비스

기타 리소스

암호화 작업