c# - Calculate a MD5 hash from a string

c# – Calculate a MD5 hash from a string

c# – Calculate a MD5 hash from a string

As per MSDN

n

Create MD5:

n

public static string CreateMD5(string input)n{n    // Use input string to calculate MD5 hashn    using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())n    {n        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);n        byte[] hashBytes = md5.ComputeHash(inputBytes);nn        // Convert the byte array to hexadecimal stringn        StringBuilder sb = new StringBuilder();n        for (int i = 0; i < hashBytes.Length; i++)n        {n            sb.Append(hashBytes[i].ToString(X2));n        }n        return sb.ToString();n    }n}n

b’

// given, a password in a stringnstring password = @1234abcd;nn// byte array representation of that stringnbyte[] encodedPassword = new UTF8Encoding().GetBytes(password);nn// need MD5 to calculate the hashnbyte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName(MD5)).ComputeHash(encodedPassword);nn// string representation (similar to UNIX format)nstring encoded = BitConverter.ToString(hash)n   // without dashesn   .Replace(-, string.Empty)n   // make lowercasen   .ToLower();nn// encoded contains the hash you wantn

c# – Calculate a MD5 hash from a string

Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.

n

string result;nusing (MD5 hash = MD5.Create())n{n    result = String.Joinn    (n        ,n        from ba in hash.ComputeHashn        (n            Encoding.UTF8.GetBytes(observedText)n        ) n        select ba.ToString(x2)n    );n}n

Related posts on stringĀ  :

Leave a Reply

Your email address will not be published.