C#

(C#) 암호화 모듈 MD5, SHA256

코딩ABC 2023. 4. 18. 08:33
반응형

C#에서 문자열을 암호화 할 때 사용할 수 있는 암호화 모듈입니다.

아래의 코드를 복사하여 사용하면 됩니다.

using System.Security.Cryptography;
using System.Text;

// MD5 암호화 128bit 암호화
public static string MD5Hash(string s)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(s));

    StringBuilder stringBuilder = new StringBuilder();

    foreach (byte b in hash)
    {
        stringBuilder.AppendFormat("{0:X2}", b);
    }
    return stringBuilder.ToString();
}

// SHA256 256bit 암호화
public static string SHA256Hash(string s)
{
    SHA256 sha = new SHA256Managed();
    byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(s));

    StringBuilder stringBuilder = new StringBuilder();

    foreach (byte b in hash)
    {
        stringBuilder.AppendFormat("{0:X2}", b);
    }
    return stringBuilder.ToString();
}
"abc123" 문자열을 암호화한 예

E99A18C428CB38D5F260853678922E03

6CA13D52CA70C883E0F0BB101E425A89E8624DE51DB2D2392593AF6A84118090

 

예제

namespace ConsoleApp1
{
    internal class Program
    {

        // MD5 암호화 128bit 암호화
        public static string MD5Hash(string s)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(s));

            StringBuilder stringBuilder = new StringBuilder();

            foreach (byte b in hash)
            {
                stringBuilder.AppendFormat("{0:X2}", b);
            }
            return stringBuilder.ToString();
        }

        // SHA256 256bit 암호화
        public static string SHA256Hash(string s)
        {
            SHA256 sha = new SHA256Managed();
            byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(s));

            StringBuilder stringBuilder = new StringBuilder();

            foreach (byte b in hash)
            {
                stringBuilder.AppendFormat("{0:X2}", b);
            }
            return stringBuilder.ToString();
        }


        static void Main(string[] args)
        {
            string s = "abc123";
            Console.WriteLine(MD5Hash(s));
            Console.WriteLine(SHA256Hash(s));
        }
    }
}

MD5 암호화

 

 

반응형