title: RSA decrypt throws 'Access denied' exception
body: <p>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 <code>RSACryptoServiceProvider</code> and it seems like that's <a href="https://stackoverflow.com/questions/41986995/implement-rsa-in-net-core">not recommended</a> anymore.</p>
  
  <p>As a result I'm switching to using the <code>GetPublicKey()</code> and <code>GetPrivateKey()</code> extension methods, but I'm having an issue with the private key.  Anytime I call <code>Decrypt</code> on the RSA instance of the private key I receive:</p>
  
  <blockquote>
    <p>{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)</p>
  </blockquote>
  
  <p>Here is a short sample of the code resulting in the exception:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>This same code works using <code>RSACryptoServiceProvider</code>.  I verified the user has access to the private key of the certificate in the store.</p>
  
  <p>What's causing this access denied exception?</p>