当我制作 x509 证书来加密和解密消息时,我收到了一些错误信息,无法解决这个问题。有人能碰巧解决这个错误吗?谢谢。
说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详情:
System.Security.Cryptography.CryptographicException: 密钥集不存在。</p>
源错误:
第 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 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);