IT

MD5 해시 계산

lottoking 2020. 7. 25. 10:21
반응형

MD5 해시 계산


다음 C # 코드를 사용하여 MD5 해시를 계산합니다. 그것은 잘 작동하고 다음과 같이 32 문자 16 진수를 생성합니다 :900150983cd24fb0d6963f7d28e17f72

string sSourceData;
byte[] tmpSource;
byte[] tmpHash;
sSourceData = "MySourceData";

//Create a byte array from source data.
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);

// and then convert tmpHash to string...

이와 같은 코드를 사용하여 16 자 16 진 (또는 12 자)을 생성하는 방법이 있습니까? 32 자 16 진 고급스러운 좋지만 고객이 코드를 입력하는 것은 지루할 것입니다!


MSDN

MD5 생성 :

   public static string CreateMD5(string input)
    {
        // Use input string to calculate MD5 hash
        using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
        {
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you want

LINQ를 사용하여 MD5 해시의 표현을 만들려고 시도했지만 LINQ 솔루션에 대한 답변은 추가 사용 가능한 솔루션의 일부에 있습니다.

string result;
using (MD5 hash = MD5.Create())
{
    result = String.Join
    (
        "",
        from ba in hash.ComputeHash
        (
            Encoding.UTF8.GetBytes(observedText)
        ) 
        select ba.ToString("x2")
    );
}

Convert.ToBase64StringMD5의 16 바이트 출력을 ~ 24 자로 변환 하는 사용할 수 있습니다 . 보안을 줄이지 않고 조금 나아졌습니다. ( j9JIbSY8HuT89/pwdC8jlw==예를 들어)


달성하려는 목표에 전적으로 달려 있습니다. 기술적으로는 MD5 해시의 결과에서 처음 12 자만 가져올 수 있지만 MD5의 사양은 32 자 문자를 생성하는 것입니다.

해시 크기를 줄이면 보안이 줄어들고 충돌 및 시스템 손상 가능성이 높아집니다.

달성하려는 목표에 대해 더 많이 알려 주시면 더 많은 도움을 드릴 수 있습니다.


지원 문자열 및 파일 스트림.

string hashString = EasyMD5.Hash("My String");

string hashFile = EasyMD5.Hash(System.IO.File.OpenRead("myFile.txt"));

-

   class EasyMD5
        {
            private static string GetMd5Hash(byte[] data)
            {
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                    sBuilder.Append(data[i].ToString("x2"));
                return sBuilder.ToString();
            }

            private static bool VerifyMd5Hash(byte[] data, string hash)
            {
                return 0 == StringComparer.OrdinalIgnoreCase.Compare(GetMd5Hash(data), hash);
            }

            public static string Hash(string data)
            {
                using (var md5 = MD5.Create())
                    return GetMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)));
            }
            public static string Hash(FileStream data)
            {
                using (var md5 = MD5.Create())
                    return GetMd5Hash(md5.ComputeHash(data));
            }

            public static bool Verify(string data, string hash)
            {
                using (var md5 = MD5.Create())
                    return VerifyMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)), hash);
            }

            public static bool Verify(FileStream data, string hash)
            {
                using (var md5 = MD5.Create())
                    return VerifyMd5Hash(md5.ComputeHash(data), hash);
            }
        }


MD5 해시는 128 비트이므로 32 자 미만으로 16 진수로 표현할 수 없습니다.


MD5 문자열에 UTF-8 인코딩을 사용하는 것이 더 낫다고 생각합니다.

public static string MD5(this string s)
{
    using (var provider = System.Security.Cryptography.MD5.Create())
    {
        StringBuilder builder = new StringBuilder();                           

        foreach (byte b in provider.ComputeHash(Encoding.UTF8.GetBytes(s)))
            builder.Append(b.ToString("x2").ToLower());

        return builder.ToString();
    }
}

System.Text.StringBuilder hash = new System.Text.StringBuilder();
        System.Security.Cryptography.MD5CryptoServiceProvider md5provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] bytes = md5provider.ComputeHash(new System.Text.UTF8Encoding().GetBytes(YourEntryString));

        for (int i = 0; i < bytes.Length; i++)
        {
            hash.Append(bytes[i].ToString("x2")); //lowerCase; X2 if uppercase desired
        }
        return hash.ToString();

.NET Core 2.1 이상에 대한 기존 답변의 더 빠른 대안 :

public static string CreateMD5(string s)
{
    using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
    {
        var encoding = Encoding.ASCII;
        var data = encoding.GetBytes(s);

        Span<byte> hashBytes = stackalloc byte[16];
        md5.TryComputeHash(data, hashBytes, out int written);
        if(written != hashBytes.Length)
            throw new OverflowException();


        Span<char> stringBuffer = stackalloc char[32];
        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashBytes[i].TryFormat(stringBuffer.Slice(2 * i), out _, "x2");
        }
        return new string(stringBuffer);
    }
}

문자열이 충분히 작다고 확신하고 encoding.GetBytes를 안전하지 않은 int GetBytes (ReadOnlySpan chars, Span bytes) 대안으로 대체하면 훨씬 더 최적화 할 수 있습니다.


StringBuilder sb= new StringBuilder();
for (int i = 0; i < tmpHash.Length; i++)
{
   sb.Append(tmpHash[i].ToString("x2"));
}

이 솔루션에는 C # 7.2가 필요하며 Span<T>. 입력 크기에 관계없이 고정 된 양의 메모리를 할당하며 허용되는 답변보다 빠릅니다. .Replace("-", string.Empty).ToLowerInvariant()필요한 경우 결과 형식을 지정하려면 여전히 호출해야 합니다.

public static string CreateMD5(ReadOnlySpan<char> input)
{
    var encoding = System.Text.Encoding.UTF8;
    var inputByteCount = encoding.GetByteCount(input);

    using (var md5 = System.Security.Cryptography.MD5.Create())
    {
        Span<byte> bytes = stackalloc byte[inputByteCount];
        Span<byte> destination = stackalloc byte[md5.HashSize / 8];

        encoding.GetBytes(input, bytes);

        // checking the result is not required because this only returns false if "(destination.Length < HashSizeValue/8)", which is never true in this case
        md5.TryComputeHash(bytes, destination, out int _bytesWritten);

        return BitConverter.ToString(destination.ToArray());
    }
}

https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.7.2

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

    static string GetMd5Hash(string input)
            {
                using (MD5 md5Hash = MD5.Create())
                {

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

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

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

                return 0 == comparer.Compare(hashOfInput, hash);

            }

참고 URL : https://stackoverflow.com/questions/11454004/calculate-a-md5-hash-from-a-string

반응형