Hash string in c#

Edy Cu picture Edy Cu · Oct 21, 2010 · Viewed 177.1k times · Source

I have a problem when trying get a hash string in c#.

I already tried a few websites, but most of them are using files to get the hash. Others that are for strings are a bit too complex. I found examples for Windows authentication for web like this:

FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text.Trim(), "md5")

I need to use a hash to make a string that contains a filename more secure. How can I do that?

Example:

string file  = "username";
string hash = ??????(username); 

Should I use another hashing algorithm and not "md5"?

Answer

Dmitry Polomoshnov picture Dmitry Polomoshnov · Jul 27, 2011
using System.Security.Cryptography;

public static byte[] GetHash(string inputString)
{
    using (HashAlgorithm algorithm = SHA256.Create())
        return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetHashString(string inputString)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in GetHash(inputString))
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}

Additional Notes

  • Since MD5 and SHA1 are obsolete and insecure algorithms, this solution uses SHA256. Alternatively, you can use BCrypt or Scrypt as pointed out in comments.
  • Also, consider "salting" your hashes and use proven cryptographic algorithms, as pointed out in comments.