[C#] MD5를 이용해서 암호화 방법

728x90
반응형

 

PHP를 이용해서 개발해보신 분들은 아시겠지만, 암호화 방법중에 기본적으로 이용하는 방식이 MD5를 이용해서 암호화 하는 방식입니다.

이번에 PHP로 개발되어 있는 사이트를 .NET Core 3.1 로 변경하는 도중, 비밀번호를 MD5를 이용해서 암호화한 부분이 있어서 C#으로 대체해보았습니다.

 


MD5 클래스

네임스페이스 : System.Security.Cryptography

위 네임스페이스에 정의 되어 있으며, 

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

 

static string GetMd5Hash(MD5 md5Hash, string input)
{
    // Convert the input string to a byte array and compute the hash.
    byte[] data = md5Hash.ComputeHash(Encoding.UTF8.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();
}

MSDN에 정의되어 있는 Sample 예제입니다.

위 예제만 이용하면 손쉽게 MD5를 암호화 해서 사용할 수 있습니다.

 

 

static void Main(string[] args)
{
    var mdHash = MD5.Create();
    string password = "1111";
    Console.WriteLine(GetMd5Hash(mdHash, password));
}


// 결과값
b59c67bf196a4758191e42f76670ceba

MD5.Create() 메소드를 이용해서, System.Security.Cryptography.MD5 해시 알고리즘의 기본 구현 인스턴스를 만들어 줄 수 있습니다. 이를 기반으로 지정된 바이트의 Hash값을 계산해서 사용하게 됩니다. 

 

 


자세한 내용은 아래 MSDN링크를 확인해주세요.

https://docs.microsoft.com/ko-kr/dotnet/api/system.security.cryptography.md5?view=netframework-4.8
728x90