2

I have a PKCS#1-formatted private key (generated by opendkim-genkey) like this

-----BEGIN RSA PRIVATE KEY-----

Base64 encoded data

-----END RSA PRIVATE KEY-----

Now I have to use it in Java to generate java.security.PrivateKey

But Java only support PKCS#8-formatted private key.

I know there is a way to convert from PKCS#8 to PKCS#1 by Java (using Bouncycastle), but is there anyway convert from PKCS#1 to PKCS#8 by Java?

Hash
  • 4,607
  • 5
  • 20
  • 39
Thanh Vũ
  • 25
  • 1
  • 5
  • You can do so using openssl with a command like `openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key`. Compare [here](https://stackoverflow.com/questions/8290435/) – Ben May 09 '18 at 10:03
  • Thank you, I know that I can do by using openssl command line. But what I ask is anyway we can do it by java. – Thanh Vũ May 09 '18 at 10:10
  • Why? You only have to do this process every few years when you re-key. Why write new Java code when an existing utility already does it correctly? – user207421 May 09 '18 at 10:19

1 Answers1

0

Disclaimer: I did not come up with this solution myself, it was written by marcoscottwright over at github. Find the original code here


You can do so using BouncyCastle given you have a PrivateKey k object.

try (ASN1InputStream asn1InputStream = new ASN1InputStream(k.getEncoded()))
{
    DERObject rsaPrivateKey = asn1InputStream.readObject();
    return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption), rsaPrivateKey).getDEREncoded();
}
Ben
  • 1,615
  • 1
  • 10
  • 22