我使用 x509 证书加密和解密消息时,出现了一些错误信息,并且无法解决这个问题。是否有人遇到过并解决了这个错误?谢谢。
描述:在当前 Web 请求的执行期间发生了未处理的异常。请查看堆栈跟踪以获取有关该错误的更多信息以及代码中它的来源。
异常详细信息:
System.Security.Cryptography.CryptographicException: keyset does not exist。
源错误:
第53行:using (RSACryptoServiceProvider rsaProviderDecrypt = (RSACryptoServiceProvider)cerDecrypt.PublicKey.Key)
{ 第54行:plainHashBytes = rsaProviderDecrypt.Decrypt(encryptedHashBytes, false); 第55行:
rsaProviderDecrypt.Clear(); 第56行:
rsaProviderDecrypt.Dispose();源文件:E:\PayUSite\PayMvcApp\Controllers\HashMessageController.cs 行号:55
堆栈跟踪:
[CryptographicException: keyset does not exist. ]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey) +0
System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean 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);
certEncrypt.PrivateKey
(加密通常使用公钥)和cerDecrypt.PublicKey
(解密通常使用私钥)。我认为它们在离开using
块时被清理了。 - jww