6

Is it possible to convert a PKCS#8 encoded RSA private key into PKCS#1? I know this can be done easily via openssl, but can it be done in Java?

rustyx
  • 80,671
  • 25
  • 200
  • 267

2 Answers2

4

Use BouncyCastle 1.50

PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(pkPair.getPrivateKey().getEncodedKey());
ASN1Encodable privateKeyPKCS1ASN1Encodable = pkInfo.parsePrivateKey();
ASN1Primitive privateKeyPKCS1ASN1 = privateKeyPKCS1ASN1Encodable.toASN1Primitive();

byte[] privateKeyPKCS1 = privateKeyPKCS1ASN1.getEncoded();
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
Hritcu Andrei
  • 172
  • 10
3

Use KeyFactory with PKCS8EncodedKeySpec (algorithm "RSA") to convert the PKCS #8 encoded private key bytes into Java objects.

Use Cipher and SecretKeyFactory (algorithm "PBEWithMD5AndDES") with PBEKeySpec, and PBEParameterSpec to create PKCS #5 encoded stuff.

martijno
  • 1,723
  • 1
  • 23
  • 53