Encode a RSA public key to DER format

2019-05-22 15:52发布

问题:

I need a RSA public key encoded into DER format.

The key-pair is generated using RSACryptoServiceProvider.

What I'm looking for is the c# equivalent to the java:

PublicKey pubKey = myPair.getPublic();
byte[] keyBytes = pubKey.getEncoded();

I have tried looking into BouncyCastle but got lost so if the solution is there any pointers are welcome.

回答1:

Using Bouncy Castle:

using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;

...

var generator = new RsaKeyPairGenerator ();
generator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));
var keyPair = generator.GenerateKeyPair ();
RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;
var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo (keyParam);
RsaBytes = info.GetEncoded ();

The last three lines are the ones who take the RSA public key and export it.