109

I want to hash given byte[] array with using SHA1 Algorithm with the use of SHA1Managed.
The byte[] hash will come from unit test.
Expected hash is 0d71ee4472658cd5874c5578410a9d8611fc9aef (case sensitive).

How can I achieve this?

public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {

    }
}
2
  • 2
    Your excpected hash is a hexadecimal value, so it doesnt matter if it's case sensitive e.g. hex(e) == hex(E) Commented Jun 25, 2013 at 8:24
  • stackoverflow.com/questions/4819794/… Commented Apr 14, 2019 at 20:55

6 Answers 6

226

For those who want a "standard" text formatting of the hash, you can use something like the following for .NET 5 and newer:

static string Hash(string input)
    => Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(input)));

This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415.

If you are stuck on pre-.NET 5 where Convert.ToHexString is not available, you can do:

static string Hash(string input)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
        var sb = new StringBuilder(hash.Length * 2);

        foreach (byte b in hash)
        {
            // can be "x2" if you want lowercase
            sb.Append(b.ToString("X2"));
        }

        return sb.ToString();
    }
}

Or for a code golfed .Net Framework version:

static string Hash(string input)
{
    var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
    return string.Concat(hash.Select(b => b.ToString("x2")));
}
Sign up to request clarification or add additional context in comments.

12 Comments

It bugs me that this solution doesn't dispose the SHA1Managed object, because it is marked as Disposable. This post could be handy when optimizing: stackoverflow.com/a/624379/991863
@Mitch If it implements the IDisposable interface then what happens in the reference source shouldn't matter. Should they ever change it for any reason such that the .Dispose() call becomes important, your previously working code is now causing a problem. Relying on looking into the bowels of a framework to determine what you can get away with is a path to a maintenance nightmare. I highly suggest following the documentation and correctly handling disposable objects, it'll save you pain in the long term.
@unenthusiastic use, Haha, thanks. I wasn't sure what the purpose of documentation was... (The code in my production applications is the one from the top, but the circumstances of the second make me comfortable enough that it would be equally supportable in all but the tightest loops. IDisposable is semi-optional when dealing with non-side-effecting classes.)
What is the "X2" for?
@ijt, X2 tells it to use two hexadecimal digits per byte. x2 means lowercase, X2 is uppercase
|
41
public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);
    }
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

6 Comments

If they want a hex string then Base64 is probably the wrong choice.
@Joey: Against the answer given by GrantThomas, the member indicated that they need to return a string
@MerveKaya: Perhaps you should explain what you mean by "it didnt work". What does the incoming byte array represent? How did you determine "SHA1Managed"-hashing the incoming byte array should give you 0d71ee4472658cd5874c5578410a9d8611fc9aef as the output?
Byte[] hash comes from unit test. In the question they wrote that expected hash is 0d71ee4472658cd5874c5578410a9d8611fc9aef. It comes from unit test
@MerveKaya: See my update on how to use Encoding when converting the hash to a string
|
19

This is what I went with. For those of you who want to optimize, check out https://stackoverflow.com/a/624379/991863.

    public static string Hash(string stringToHash)
    {
        using (var sha1 = new SHA1Managed())
        {
            return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));
        }
    }

1 Comment

I had to use BitConverter.ToString(sha1.ComputeHash(bytes)).Replace("-", "") since I didn't want the dashes introduced by BitConverter. After that it worked like a charm! Thanks!
9

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

Comments

9

Fastest way is this :

    public static string GetHash(string input)
    {
        return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
    }

For Small character output use x2 in replace of of X2

3 Comments

SHA1Managed implements IDisposable, so you would probably want to dispose it when done with it to free up resources.
It's not the fastest way, it's merely packed into a single line.
@quetzalcoatl well, yeah :)
4

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.