Skip to content

Instantly share code, notes, and snippets.

@jimmyMaci
Last active July 24, 2018 16:32
Show Gist options
  • Save jimmyMaci/1e2273326cbdaccf925d38221adceeb0 to your computer and use it in GitHub Desktop.
Save jimmyMaci/1e2273326cbdaccf925d38221adceeb0 to your computer and use it in GitHub Desktop.
Convert a PKCS#1 formatted java private key to PKCS#8
In BouncyCastle version 1.60 you can convert a PKCS#1 formatted private key to PKCS#8 with this method:
```
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