Search code examples
javarsabouncycastle

Bouncycastle: how to create an encrypted PKCS8 representation of an RSA private key?


In my application I have a AsymmetricCipherKeyPair keyPair and KeyParameter key. From that, I need to generate a PKCS#8 representation of the private key in the form

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

Can anybody give me a hint on how I could accomplish that?


Solution

  • You can use org.bouncycastle.crypto.util.PrivateKeyInfoFactory to create a PrivateKeyInfo object from the private KeyParameter. getEncoded() on that will return the bytes that represent the PKCS#8 version of the key.

    The PEM headings you give do suggest you might want an OpenSSL encoding instead - in that case you should be able to use the BC PEMWriter in conjunction with the PrivateKeyInfo object, or in conjunction with a PrivateKey object generated using KeyFactory with the encoding of PrivateKeyInfo passed in as a PKCS8EncodedKeySpec (sort of depends on what version of BC you are using).

    Regards,

    David