When I generate an RSA key pair using the Java API, the public key is encoded in the X.509 format and the private key is encoded in the PKCS#8 format. I'm looking to encode both as PKCS#1. Is this possible? I've spent a considerable amount of time going through the Java docs but haven't found a solution. The result is the same when I use the Java and the Bouncy Castle providers.
Here is a snippet of the code:
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA","BC");
keygen.initialize(1024);
KeyPair pair = keygen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
byte[] privBytes = priv.getEncoded();
byte[] pubBytes = pub.getEncoded();
The two resulting byte arrays are formatted as X.509 (public) and PKCS#8 (private).
Any help would be much appreciated. There are some similar posts but none really answer my question.
Thank You
Best Answer
You will need BouncyCastle:
The code snippets below have been checked and found working with Bouncy Castle 1.52.
Private key
Convert private key from PKCS8 to PKCS1:
Convert private key in PKCS1 to PEM:
Check with command line OpenSSL that the key format is as expected:
Public key
Convert public key from X.509 SubjectPublicKeyInfo to PKCS1:
Convert public key in PKCS1 to PEM:
Check with command line OpenSSL that the key format is as expected:
Thanks
Many thanks to the authors of the following posts:
Those posts contained useful, though sometimes outdated info (i.e. for older versions of BouncyCastle), that helped me to construct this post.