Hash string in c#

C#StringHash

C# Problem Overview


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"?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

The fastest way, to get a hash string for password store purposes, is a following code:

    internal static string GetStringSha256Hash(string text)
    {
        if (String.IsNullOrEmpty(text))
            return String.Empty;

        using (var sha = new System.Security.Cryptography.SHA256Managed())
        {
            byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hash = sha.ComputeHash(textData);
            return BitConverter.ToString(hash).Replace("-", String.Empty);
        }
    }

Remarks:

  • if the method is invoked often, the creation of sha variable should be refactored into a class field;
  • output is presented as encoded hex string;

Solution 3 - C#

I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.

Just use the GetHashCode method.

Like this:

string hash = username.GetHashCode();

Solution 4 - C#

I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.

See https://stackoverflow.com/questions/667887/aes-in-asp-net-with-vb-net for more information about encryption in .NET.

Solution 5 - C#

The shortest and fastest way ever. Only 1 line!

    public static string StringSha256Hash(string text) =>
        string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Solution 6 - C#

If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2" with "X2".)

public static string SHA256ToString(string s) 
{
    using (var alg = SHA256.Create())
        return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}

or:

public static string SHA256ToString(string s)
{            
    using (var alg = SHA256.Create())
        return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}

Solution 7 - C#

All the hashing code samples here are outdated. In.NET 5, a new way of hashing data is provided to us which is double fast and does zero memory allocation. ain't that cool? You just need to use the new static HashData(byte[]) on your favorite hashing algorithm class.

byte[] buffer = Encoding.UTF8.GetBytes(input);
byte[] digest = SHA256.HashData(buffer);

Microsoft has a new rule in its analyzer to detect legacy usages and replace them with the new API.

Solution 8 - C#

//Secure & Encrypte Data
    public static string HashSHA1(string value)
    {
        var sha1 = SHA1.Create();
        var inputBytes = Encoding.ASCII.GetBytes(value);
        var hash = sha1.ComputeHash(inputBytes);
        var sb = new StringBuilder();
        for (var i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdy CuView Question on Stackoverflow
Solution 1 - C#Dmitry PolomoshnovView Answer on Stackoverflow
Solution 2 - C#andrew.foxView Answer on Stackoverflow
Solution 3 - C#Cyril GuptaView Answer on Stackoverflow
Solution 4 - C#Pieter van GinkelView Answer on Stackoverflow
Solution 5 - C#Erçin DedeoğluView Answer on Stackoverflow
Solution 6 - C#BabakView Answer on Stackoverflow
Solution 7 - C#Ehsan MirsaeediView Answer on Stackoverflow
Solution 8 - C#Soufiane NeffarView Answer on Stackoverflow