다음을 통해 공유


MD5 클래스

MD5 해시 알고리즘의 모든 구현이 상속될 추상 클래스를 나타냅니다.

네임스페이스: System.Security.Cryptography
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public MustInherit Class MD5
    Inherits HashAlgorithm
‘사용 방법
Dim instance As MD5
[ComVisibleAttribute(true)] 
public abstract class MD5 : HashAlgorithm
[ComVisibleAttribute(true)] 
public ref class MD5 abstract : public HashAlgorithm
/** @attribute ComVisibleAttribute(true) */ 
public abstract class MD5 extends HashAlgorithm
ComVisibleAttribute(true) 
public abstract class MD5 extends HashAlgorithm

설명

해시 함수는 임의의 길이의 이진 문자열을 고정된 길이의 작은 이진 문자열에 매핑합니다. 암호화 해시 함수는 동일한 값에 해시하는 두 개의 다른 입력을 연산적으로 찾지 못하는 속성, 즉 해당 데이터가 일치하면 두 집합의 데이터 해시도 일치하는 속성을 갖습니다. 데이터에 작은 변경이 있으면 해시에 예측할 수 없는 커다란 변경이 발생합니다.

MD5 알고리즘에 대한 해시 크기는 128비트입니다.

MD5 클래스의 ComputeHash 메서드는 해시를 16바이트 배열로 반환합니다. 일부 MD5 구현에서는 32자로 된 16진수 형식의 해시를 생성합니다. 이러한 구현을 사용하려면 ComputeHash 메서드의 반환 값 형식을 16진수 값으로 지정합니다.

예제

다음 코드 예제에서는 문자열의 MD5 해시 값을 계산하고 해시를 32자로 된 16진수 형식의 문자열로 반환합니다. 이 코드 예제에서 만든 해시 문자열은 모든 플랫폼에서 32자로 된 16진수 형식의 해시 문자열을 만드는 모든 MD5 해시 함수와 호환됩니다.

Imports System
Imports System.Security.Cryptography
Imports System.Text

Module Example

    ' Hash an input string and return the hash as
    ' a 32 character hexadecimal string.
    Function getMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5 object.
        Dim md5Hasher As MD5 = MD5.Create()

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function


    ' Verify a hash against a string.
    Function verifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = getMd5Hash(input)

        ' Create a StringComparer an comare the hashes.
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase

        If 0 = comparer.Compare(hashOfInput, hash) Then
            Return True
        Else
            Return False
        End If

    End Function



    Sub Main()
        Dim source As String = "Hello World!"

        Dim hash As String = getMd5Hash(source)

        Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".")

        Console.WriteLine("Verifying the hash...")

        If verifyMd5Hash(source, hash) Then
            Console.WriteLine("The hashes are the same.")
        Else
            Console.WriteLine("The hashes are not same.")
        End If

    End Sub
End Module
' This code example produces the following output:
'
' The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
' Verifying the hash...
' The hashes are the same.
using System;
using System.Security.Cryptography;
using System.Text;

class Example
{
    // Hash an input string and return the hash as
    // a 32 character hexadecimal string.
    static string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

    // Verify a hash against a string.
    static bool verifyMd5Hash(string input, string hash)
    {
        // Hash the input.
        string hashOfInput = getMd5Hash(input);

        // Create a StringComparer an comare the hashes.
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;

        if (0 == comparer.Compare(hashOfInput, hash))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    static void Main()
    {
        string source = "Hello World!";
        
        string hash = getMd5Hash(source);

        Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");

        Console.WriteLine("Verifying the hash...");

        if (verifyMd5Hash(source, hash))
        {
            Console.WriteLine("The hashes are the same.");
        }
        else
        {
            Console.WriteLine("The hashes are not same.");
        }
        
    }
}
// This code example produces the following output:
//
// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
// Verifying the hash...
// The hashes are the same.

상속 계층 구조

System.Object
   System.Security.Cryptography.HashAlgorithm
    System.Security.Cryptography.MD5
       System.Security.Cryptography.MD5CryptoServiceProvider

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0에서 지원

참고 항목

참조

MD5 멤버
System.Security.Cryptography 네임스페이스

기타 리소스

암호화 서비스