Q: Key is not a valid public or private key I am trying to import key pair created by RSACryptoServiceProvider into ECDiffieHellmanOpenSsl:
RSACryptoServiceProvider keyPair = EncryptionTools.GenerateRSAKeyPair(4096);

ECDiffieHellmanOpenSsl alice = new ECDiffieHellmanOpenSsl();
int publicBytesReadAlice = 0;
alice.ImportSubjectPublicKeyInfo(new ReadOnlySpan<byte>(keyPair.ExportSubjectPublicKeyInfo()), out publicBytesReadAlice);formát
int privateBytesRead = 0;
alice.ImportPkcs8PrivateKey(new ReadOnlySpan<byte>(keyPair.ExportPkcs8PrivateKey()), out privateBytesRead);

It is throwing this error on fifth line:

System.Security.Cryptography.CryptographicException: Key is not a valid public or private key.

I don't know where the issue is because docs say:

*

*ECDiffieHellman.ImportSubjectPublicKeyInfo: Imports the public key from an X.509 SubjectPublicKeyInfo structure after decryption, replacing the keys for this object. Source is: The bytes of an X.509 SubjectPublicKeyInfo structure in the ASN.1-DER encoding.

*AsymmetricAlgorithm.ExportSubjectPublicKeyInfo: Exports the public-key portion of the current key in the X.509 SubjectPublicKeyInfo format.

The same thing happens when trying to import RSA private key, which is supposed to be in Pkcs8 format.
Any idea how to correctly export/serialize keys and pass it to ECDiffieHellmanOpenSsl? And any idea how to serialize it to string?

A: RSA keys and ECDH-compatible keys are extremely different beasts.  It's not even quite "square peg, round hole", but more like "color green, round hole".  They're both asymmetric keys, which means they're both compatible with the SPKI and PKCS8 formats, though.  (Both of those formats are basically "here's the kind of key I am" and "here's some data of the format appropriate to that key")

*

*ECDH can load in any key created by an ECDsa or ECDH instance.

*ECDsa can load in any key created by an ECDsa instance, and most keys created by an ECDH instance.

*RSA can only load keys created by an RSA instance.

*DSA can only load keys created by a DSA instance.

(for all of those statements the keys can also be created by a compatible notion on some other platform or some other library set).
So, if you want to serialize an ECDH, just start by creating an ECDH (e.g. ECDiffieHellman.Create(ECCurve.NamedCurves.nistP521)).
For text versions, .NET 7 is adding straight-to-PEM versions (e.g. key.ExportSubjectPublicKeyInfoPem()).  For earlier versions you can use PemEncoding, e.g. PemEncoding.Write("PUBLIC KEY", key.ExportSubjectPublicKeyInfo()).
