【发布时间】:2020-01-11 11:07:56
【问题描述】:
从我的证书中,我想检索公钥然后解密我的消息。 我使用 X509Certificate2 从我的证书中获取信息,然后使用 RSA 类进行解密,但出现错误:密钥不存在。
我在这里看到Best way to initiate RSACryptoServiceProvider from x509Certificate2?:
“从 .NET 4.6 开始,不再建议按照 RSACryptoServiceProvider 的建议进行强制转换。现在这更是一个问题,因为有多个版本的 .NET(例如 .NET Core)。
通过这种方式转换为 RSACryptoServiceProvider,您很有可能会遇到此转换异常(取决于所使用的平台和库):
Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'
原因是每个平台的实际实现可能不同,在 Windows 上使用 RSACng。"
所以我尝试使用 RSA 类而不是 RSACryptoServiceProvider。
string pemcert;
X509Certificate2 Lcertificate = new X509Certificate2(Encoding.UTF8.GetBytes(pemcert));
//my message
byte[] bytesCypherText = Convert.FromBase64String(b64_crypted_text);
using (RSA LRSApublicKeyProvider = Lcertificate.GetRSAPublicKey())
{
string decrypted = Encoding.UTF8.GetString((LRSApublicKeyProvider.Decrypt(bytesCypherText, RSAEncryptionPadding.Pkcs1)));
return decrypted;
}
我有这个错误:
Certificat: Error => key doesn't exist
/ System.Security.Cryptography.CryptographicException
Certificat. StackTrace : à System.Security.Cryptography.NCryptNative.DecryptData[T](SafeNCryptKeyHandle key, Byte[] data, T& paddingInfo, AsymmetricPaddingMode paddingMode, NCryptDecryptor`1 decryptor)
à System.Security.Cryptography.NCryptNative.DecryptDataPkcs1(SafeNCryptKeyHandle key, Byte[] data)
à System.Security.Cryptography.RSACng.Decrypt(Byte[] data, RSAEncryptionPadding padding)
à EA_Crocodile.CryptoHelper.RSADecryptJEAM(String b64_crypted_text, String pemcert)
如果我这样做:
Lcertificate.GetPublicKeyString() I have the key: 3082020A0282020100B39A5....
如果我这样做:
Lcertificate.GetRSAPublicKey().ToString(): System.Security.Cryptography.RSACng
为什么 GetRSAPublicKey() 似乎没有公钥? 是不是最好的解密方式?
【问题讨论】:
标签: c# rsa x509certificate2