gpt4 book ai didi

.net - RSACryptoServiceProvider.Decrypt() 为 "System.Security.Cryptography.CryptographicException: Bad Key."

转载 作者:行者123 更新时间:2023-12-02 05:47:57 24 4
gpt4 key购买 nike

我正在研究 RSA 加密/解密和证书。具体来说,我尝试使用证书的公钥进行加密,然后,当尝试使用与该证书对应的私钥进行解密时,出现错误:

System.Security.Cryptography.CryptographicException: Bad Key.

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int3
2 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey)
at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)

代码是:

private void TestCertificates2()
{
//////////////////////////////////////////////////////
// SENDER CODE
//////////////////////////////////////////////////////

// get certificate
var certSender = new X509Certificate2(@"C:\Test.cer");

// encrypt with public key
var providerSender = (RSACryptoServiceProvider)certSender.PublicKey.Key;
var plainSender = Encoding.Default.GetBytes("this is plain text");
var cipher = providerSender.Encrypt(plainSender, false);

//////////////////////////////////////////////////////
// RECEIVER CODE
//////////////////////////////////////////////////////

// get certificate
var store = new X509Store("MY", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certReceiver = store.Certificates.Find(X509FindType.FindBySubjectName, "Test Subject", false)[0];

// decrypt with private key
var providerReceiver = (RSACryptoServiceProvider)certReceiver.PrivateKey;
var plainReceiver = providerReceiver.Decrypt(cipher, false);

// check they are same
if (plainSender.Equals(plainReceiver))
{
Console.WriteLine("Same!");
}
}

仅供引用,证书是通过创建并安装的

makecert.exe Test.cer -n "CN=Test Subject" -sr LocalMachine -ss My

有人能发现我做错了什么吗?提前致谢!

最佳答案

好的,找到问题所在:需要告诉 makecert1) 证书的主题 key 类型用于“Exchange”2) 将私钥标记为可导出

所以 makecert 调用看起来像

makecert.exe Test.cer -r -n "CN=Test Subject" -sr LocalMachine -ss My -sky Exchange -pe

关于.net - RSACryptoServiceProvider.Decrypt() 为 "System.Security.Cryptography.CryptographicException: Bad Key.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661637/

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