Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a PKCS#8 encoded RSA key into PKCS#1 in Java?

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?

like image 418
rustyx Avatar asked Mar 11 '11 09:03

rustyx


2 Answers

Use BouncyCastle 1.50

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

byte[] privateKeyPKCS1 = privateKeyPKCS1ASN1.getEncoded();
like image 182
Hritcu Andrei Avatar answered Sep 26 '22 20:09

Hritcu Andrei


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.

like image 24
martijno Avatar answered Sep 23 '22 20:09

martijno