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
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.
The code appears to work fine. The problem could be:
MDS.Create()
to inside GetSignature()
SignService
or _hashAlgo
)?
If so do not dispose it or recreate it when needed.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With