【发布时间】:2012-08-26 02:17:29
【问题描述】:
我收到 ObjectDisposedException:安全句柄已关闭。
这是我的代码:
我正在尝试创建一个接口和实现类,使我能够获取一个字符串,将一个已知密钥附加到它,计算该字符串和密钥的 MD5 哈希,并返回计算出的哈希:
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();
}
}
谢谢
【问题讨论】:
-
哪行代码抛出异常?
-
hashed.ToHexString()是扩展方法吗?我粘贴了您的代码,但该方法不存在... -
您好,这是一种扩展方法。抛出的行是: var hashed = _hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(strWithKey));
-
您的代码有效。问题应该在您向我们展示的内容之外的某个地方。很可能,
_hashAlgo某时被处置... -
这几乎肯定是一个多线程问题,这将导致这个异常。查看Finalizer issue under stress?的答案。
标签: c# hash cryptography md5 cryptographic-hash-function