From my certificat, I want to retrieve the public key then decrypt my message. I use X509Certificate2 to get information from my certificat then RSA class to decrypt but I have the error : key doesn't exist.
I see here Best way to initiate RSACryptoServiceProvider from x509Certificate2?:
"Since .NET 4.6, casting to RSACryptoServiceProvider as suggested by is no longer recommended. This is even more an issue now since there are several versions of .NET (such as .NET Core).
By casting to RSACryptoServiceProvider that way, there is a good chance you might get this cast exception (depending on the platform and libraries used):
Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'
The reason is the actual implementation could be different from each platform, on Windows RSACng is used."
So I try to use the RSA class instead of 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;
}
I have this error :
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)
If I do :
Lcertificate.GetPublicKeyString() I have the key: 3082020A0282020100B39A5....
If I do :
Lcertificate.GetRSAPublicKey().ToString(): System.Security.Cryptography.RSACng
why the GetRSAPublicKey() seems not have the public key ? Is it the best way to decrypt ?