Search code examples
c#.netbouncycastle

Inverse operation to `PublicKeyFactory.CreateKey()`


Using Bouncycastle with C#, what is the inverse operation to:

byte[] publicKey;
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKey);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;

I.e. I have a RsaKeyParameters object containing a public key and want to convert it to a byte array in such a way that I could feed it back in to PublicKeyFactory.CreateKey()


Solution

  • The inverse operation for public keys should be:

    byte[] publicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rsaKeyParameters).GetDerEncoded();
    

    That factory class is in the Org.BouncyCastle.X509 namespace.

    For private keys, the corresponding factory classes are Org.BouncyCastle.Security.PrivateKeyFactory and Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory/EncryptedPrivateKeyInfoFactory.