Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectDisposedException When using MD5 ComputeHash

I am getting ObjectDisposedException: Safe handle has been closed.

This is my code:

I am trying to create an interface and implementing class that will enable me to get a string, attach to it a known key, compute MD5 hash for this string and the key, and return the computed hash:

public interface ISignService
{
    string GetSignature(string str);
}

public class SignService : ISignService
{
    private readonly ISignSettings _signSettings;
    private readonly HashAlgorithm _hashAlgo;


    public SignService(ISignSettings signSettings)
    {
        _signSettings = signSettings;
        _hashAlgo = MD5.Create();
    }

    public string GetSignature(string str)
    {
        var strWithKey = str + _signSettings.EncryptionKey;

        var hashed = _hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(strWithKey));

        return hashed.ToHexString();
    }
}

Thanks

like image 492
user1625867 Avatar asked Aug 31 '12 09:08

user1625867


2 Answers

Your code is not thread-safe. _hashAlgo cannot be shared between threads. Note that the exception you see is not the only problem that can result; I believe that problem also can lead to incorrect hash values. You need to either create a new HashAlgorithm object each time or look into thread locals to create one instance per thread.

like image 66
perelman Avatar answered Nov 05 '22 22:11

perelman


The code appears to work fine. The problem could be:

  1. Is the object being serialized and deserialized between construction and use? If so, move the MDS.Create() to inside GetSignature()
  2. Is the object being disposed (either SignService or _hashAlgo)? If so do not dispose it or recreate it when needed.
like image 39
akton Avatar answered Nov 05 '22 23:11

akton