Search code examples
c#cryptographyder

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.


Solution

  • 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.