Search code examples
c#encryptionbouncycastle

Get DER-encoded public key


Using BounceCastle I have the following code working. It generates a keypair and return the ASN.1 DER-encoded format.

//Generate new key
var generator = new RsaKeyPairGenerator ();
generator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));
var keyPair = generator.GenerateKeyPair ();

//Save private key for later use
keyParameters = (RsaKeyParameters)keyPair.Private;

//Export ASN.1 DER-encoded
SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
return info.GetEncoded ();

It has been tested and works with third party software.

My question is: how can I make the inverse of the above encoding. Having the encoded public key, how do I get the public key into a RsaKeyParameters.

I guess I'm about to do something similar to this.

SubjectPublicKeyInfo s = new SubjectPublicKeyInfo(????, publicKeyBytes);
RsaKeyParameters key = (RsaKeyParameters)PublicKeyFactory.CreateKey(s);

So if this is close I need to know what to put in ????, it expects an object of type AlgorithmIdentifier.


Solution

  • Thanks to this answer I got the following code:

            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(req.PublicKey);
            RsaKeyParameters key = (RsaKeyParameters) asymmetricKeyParameter;