【发布时间】:2012-08-19 19:37:44
【问题描述】:
当我制作 x509 证书来加密和解密消息时,我收到了一些错误信息,无法解决这个问题。有人能碰巧解决这个错误吗?谢谢。
说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详情:
System.Security.Cryptography.CryptographicException: 密钥集不存在。
来源错误:
第 53 行:使用 (RSACryptoServiceProvider rsaProviderDecrypt = (RSACryptoServiceProvider)cerDecrypt.PublicKey.Key) 第 54 行:
{ 第 55 行:plainHashBytes = rsaProviderDecrypt.Decrypt(encryptedHashBytes, false);第 56 行:
rsaProviderDecrypt.Clear();第 57 行:
rsaProviderDecrypt.Dispose();源文件: E:\PayUSite\PayMvcApp\Controllers\HashMessageController.cs 行:55
堆栈跟踪:
[CryptographicException:密钥集不存在。 ]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 小时) +41
System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey) +0
System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(字节[] rgb, 布尔 fOAEP) +579
源代码:
string docFile = Server.MapPath("~/docx/DirectAccess_StepByStep.doc");
HashAlgorithm hash = HashAlgorithm.Create("SHA1");
byte[] hashedBytes;
using (FileStream fs = new FileStream(docFile, FileMode.Open))
{
//compute message hash value
hashedBytes = hash.ComputeHash(fs);
hash.Dispose();
fs.Close();
}
string hashedString = Convert.ToBase64String(hashedBytes);
//encrypt message digest
string priKeyFile = Server.MapPath("~/certificate/WosMiddle.pfx");
X509Certificate2 certEncrypt = new X509Certificate2(priKeyFile, "123456");
byte[] encryptedHashBytes;
using (RSACryptoServiceProvider rsaProviderEncrypt = (RSACryptoServiceProvider)certEncrypt.PrivateKey)
{
encryptedHashBytes = rsaProviderEncrypt.Encrypt(hashedBytes, false);
rsaProviderEncrypt.Dispose();
}
//decrypt message digest
string pubKeyFile = Server.MapPath("~/certificate/WosMiddle-pubkey.cer");
X509Certificate2 cerDecrypt = new X509Certificate2(pubKeyFile);
byte[] plainHashBytes;
using (RSACryptoServiceProvider rsaProviderDecrypt = (RSACryptoServiceProvider)cerDecrypt.PublicKey.Key)
{
//***will throw error message here...***
plainHashBytes = rsaProviderDecrypt.Decrypt(encryptedHashBytes, false);
rsaProviderDecrypt.Dispose();
}
//verify message whether was modified
string docFile2 = Server.MapPath("~/docx/DirectAccess_StepByStep.doc");
HashAlgorithm hash2 = HashAlgorithm.Create("SHA1");
byte[] hashedBytes2;
using (FileStream fs2 = new FileStream(docFile2, FileMode.Open))
{
//compute message hash value
hashedBytes2 = hash.ComputeHash(fs2);
fs2.Close();
}
//compare hash value
bool isEqual = plainHashBytes.SequenceEqual(hashedBytes2);
【问题讨论】:
-
我以前见过这种情况。在Cryptographic Interoperability: Digital Signatures 搜索“密钥集不存在”。我认为打开了几个句柄。当它们被垃圾收集时,共享资源会被清理多次(这不起作用)。我会仔细查看
certEncrypt.PrivateKey(加密通常使用公钥)和cerDecrypt.PublicKey(解密通常使用私钥)。我认为它们在离开using块时已被清理干净。
标签: c# x509certificate