Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Last active June 23, 2022 14:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save markscottwright/4bd563fa91e9a72bf1ce12a0ff6567aa to your computer and use it in GitHub Desktop.
Save markscottwright/4bd563fa91e9a72bf1ce12a0ff6567aa to your computer and use it in GitHub Desktop.
How to convert a java private key from PKCS#1 encoding to PKCS#8

I had some historical key material data in pkcs#1 format that needed to be in pkcs#8 for input into another system. Here's how to do it, using BouncyCastle:

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.security.PrivateKey;


    public static byte[] toPkcs8(PrivateKey k) throws IOException {
        final String keyFormat = k.getFormat();

        if (keyFormat.equals("PKCS#8")) {
            return k.getEncoded();
        }

        else if (keyFormat.equals("PKCS#1")) {
            try (ASN1InputStream asn1InputStream = new ASN1InputStream(k.getEncoded())) {
                DERObject rsaPrivateKey = asn1InputStream.readObject();
                return new PrivateKeyInfo(
                        new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption), rsaPrivateKey)
                                .getDEREncoded();
            }
        }

        throw new IOException("Unexpected key format" + keyFormat);
    }
@jimmyMaci
Copy link

In BouncyCastle version 1.60 there is not method getDEREncoded for the key format PKCS#1. This is another way for convert it:

public static byte[] toPKCS8Format(final PrivateKey privateKey) throws IOException
	{
		String keyFormat = privateKey.getFormat();
		if (keyFormat.equals("PKCS#1")) {
			final byte[] encoded = privateKey.getEncoded();
			final PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(encoded);
			final ASN1Encodable asn1Encodable = privateKeyInfo.parsePrivateKey();
			final ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
			final byte[] privateKeyPKCS8Formatted = asn1Primitive.getEncoded(ASN1Encoding.DER);
			return privateKeyPKCS8Formatted;			
        }
		return privateKey.getEncoded();
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment