Search code examples
javasecurityrsajcepkcs#8

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?


Solution

  • Use BouncyCastle 1.50

    PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(pkPair.getPrivateKey().getEncodedKey());
    ASN1Encodable privateKeyPKCS1ASN1Encodable = pkInfo.parsePrivateKey();
    ASN1Primitive privateKeyPKCS1ASN1 = privateKeyPKCS1ASN1Encodable.toASN1Primitive();
    
    byte[] privateKeyPKCS1 = privateKeyPKCS1ASN1.getEncoded();