hultqvist hultqvist - 5 months ago 54
C# Question

Encode a RSA public key to DER format

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.

Answer Source

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(), 2048));
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download