gpt4 book ai didi

c# - 为什么.NET RSACryptoServiceProvider 会抛出 "Safe handle has been closed"异常?

转载 作者:行者123 更新时间:2023-12-02 09:24:17 28 4
gpt4 key购买 nike

以下方法用于使用“SHA1”根据公钥验证数据。第一次调用该方法时可以正常工作。但是,当第二次及后续调用该方法时,会显示以下行

isVerified = RSA.VerifyData(tokenData, CryptoConfig.MapNameToOID(hashType), signature);

导致此异常

{"Safe handle has been closed"} System.Exception {System.ObjectDisposedException}

想想我可能做错了什么?

internal static bool VerifyTokenData(byte[] tokenData, byte[] signature, string hashType)
{
try
{
bool isVerified = false;

using (RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)CompanyAuthentication.publicKey)
{
isVerified = RSA.VerifyData(tokenData, CryptoConfig.MapNameToOID(hashType), signature);
}

return isVerified;
}
catch (CryptographicException cryptoExc)
{
throw new InvalidOperationException("Exception verifying token data", cryptoExc);
}
catch (Exception exc)
{
throw new InvalidOperationException("Exception verifying token data", exc);
}
}

使用的公钥被加载到类变量中

internal static void LoadKeys()
{
try
{
X509Certificate2 certificate = new X509Certificate2();
lock (CompanyAuthentication.thisLock)
{
certificate.Import(System.Configuration.ConfigurationManager.AppSettings["companyKeyFilePath"].ToString(), System.Configuration.ConfigurationManager.AppSettings["companyKeyFilePassword"].ToString(), X509KeyStorageFlags.UserKeySet);
CompanyAuthentication.publicKey = certificate.PublicKey.Key;
CompanyAuthentication.privateKey = certificate.PrivateKey;
}
}
catch (CryptographicException cryptoExc)
{
throw new InvalidOperationException("Exception creating public/private keys", cryptoExc);
}
catch (Exception exc)
{
throw new InvalidOperationException("Exception creating public/private keys", exc);
}
}

编辑:这是修改后的代码,可以正常运行。它每次都会加载 key 文件,而不是在类构造函数中加载一次。

    SalesNetAuthentication.LoadKeys();
using (RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)SalesNetAuthentication.publicKey)
{
isVerified = RSA.VerifyData(tokenData, CryptoConfig.MapNameToOID(hashType), signature);
}

最佳答案

由于您有 using (RSACryptoServiceProvider RSA = ...),因此当 using 作用域结束时,它会处理该对象。

解决方案是删除using,以便该对象可以在后续尝试中使用,或者在每次需要使用时重新创建该对象。

关于c# - 为什么.NET RSACryptoServiceProvider 会抛出 "Safe handle has been closed"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466041/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com