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
RSA rsa = RSA.Create();
File.WriteAllBytes("TestPrivateKey", rsa.ExportRSAPrivateKey());
File.WriteAllBytes("TestPublicKey", rsa.ExportRSAPublicKey());
rsa.ImportRSAPrivateKey(File.ReadAllBytes("TestPrivateKey"), out _);
rsa.ImportRSAPublicKey(File.ReadAllBytes("TestPublicKey"), out _);
string textToBeEncrypted = "Hello World";
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);
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?