I'm switching some .NET Framework libraries over to .NET Standard. One of my libraries handles JSON Web Tokens (JWT) using a certificate store on the local machine. The library was using RSACryptoServiceProvider
and it seems like that's not recommended anymore.
As a result I'm switching to using the GetPublicKey()
and GetPrivateKey()
extension methods, but I'm having an issue with the private key. Anytime I call Decrypt
on the RSA instance of the private key I receive:
{Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Access denied at System.Security.Cryptography.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, Byte[] input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, EncryptOrDecryptAction encryptOrDecrypt) at System.Security.Cryptography.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, EncryptOrDecryptAction encryptOrDecrypt) at System.Security.Cryptography.RSACng.Decrypt(Byte[] data, RSAEncryptionPadding padding)
Here is a short sample of the code resulting in the exception:
public X509Certificate2 GetCert() {
using (var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine)) {
certStore.Open(OpenFlags.ReadOnly);
var certMatches = certStore.Certificates.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
return certMatches[0];
}
}
var cert = GetCert();
var publicKey = cert.GetRSAPublicKey();
var encryptedBytes = publicKey.Encrypt(bytes, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA256);
var privateKey = cert.GetRSAPrivateKey();
// Exception on this line. :(
var decryptedBytes = privateKey.Decrypt(encryptedBytes, System.Security.Cryptography.RSAEncryptionPadding.OaepSHA256);
This same code works using RSACryptoServiceProvider
. I verified the user has access to the private key of the certificate in the store.
What's causing this access denied exception?