Quantcast
Viewing all articles
Browse latest Browse all 9

C# Hash String to Hexadecimal String

Outputs a 40 character hexadecimal hash string using the MD5 algorithm.

private string ToHash(string source)
{
    byte[] bytes;
    char[] c;
    byte b;
	
    //using (SHA1 m = new System.Security.Cryptography.SHA1Managed())
    using (MD5 m = System.Security.Cryptography.MD5.Create())
    {
        bytes = m.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(source));
        c = new char[bytes.Length * 2];
        for (int i = 0; i < bytes.Length; ++i)
        {
            b = ((byte)(bytes[i] >> 4));
            // replace 0x57 with 0x37 to output uppercase
            c[i * 2] = (char)(b > 9 ? b + 0x57 : b + 0x30);
            b = ((byte)(bytes[i] & 0xF));
            // replace 0x57 with 0x37 to output uppercase
            c[i * 2 + 1] = (char)(b > 9 ? b + 0x57 : b + 0x30);
        }
    }
    return new string(c);
}

Viewing all articles
Browse latest Browse all 9

Trending Articles