GSI

MD5 샘플 코드

C# 2009. 12. 23. 13:44 |


--선언--
using System.Security.Cryptography;

--코드--
        #region MD5 메소드
        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;
            }
        }
        #endregion

        #region MD5 테스트 블록
        private void button1_Click(object sender, EventArgs e)
        {
            // 암호화 문자열을 가져온다.
            string convmd5 = getMd5Hash(textBox1.Text);

            // 암호화된 내용을 출력한다.
            textBox2.Text = convmd5;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 해당 문자열을 가져와서 암호화된 내용과 비교 한다.
            if (verifyMd5Hash(textBox3.Text, textBox2.Text) == true)
            {
                MessageBox.Show("맞습니다.");
            }
            else
            {
                MessageBox.Show("틀립니다.");
            }
        }
        #endregion

Posted by gsi
: