title: Importing and Exporting RSA Keys in C#
body: <p>I am trying to export and reimport public and private RSA keys. I do it using the System.Security.Cryptography.RSA class. But it does not work as expected. Please assume the following code example</p>
  <pre><code>RSA rsa = RSA.Create();
  File.WriteAllBytes(&quot;TestPrivateKey&quot;, rsa.ExportRSAPrivateKey());
  File.WriteAllBytes(&quot;TestPublicKey&quot;, rsa.ExportRSAPublicKey());
  rsa.ImportRSAPrivateKey(File.ReadAllBytes(&quot;TestPrivateKey&quot;), out _);
  rsa.ImportRSAPublicKey(File.ReadAllBytes(&quot;TestPublicKey&quot;), out _);
  
  string textToBeEncrypted = &quot;Hello World&quot;;
  byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(textToBeEncrypted);
  byte[] encryptedBytes = rsa.Encrypt(bytesToBeEncrypted, RSAEncryptionPadding.OaepSHA256);
  
  byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256);
  string result = Encoding.UTF8.GetString(decryptedBytes);
  </code></pre>
  <p>The encrytion and decryption works fine when I do not use the export and import. But when I use them I get an Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException stating that the key was not found on rsa.Decrypt function.
  I am not an expert on cryptography and I know there are other ways to achieve that I am doing (there are lots of examples out there), but they are all somewhat complex. This here seems pretty straight forward. But why does it not work? Should the key not be the same after reimport?</p>