How can I read a BouncyCastle public key PEM file using JCA?

In one of our applications, private keys are stored using the BouncyCastle PEMWriter. At the moment, I am studying whether we can get rid of the BouncyCastle dependency, since Java 7 seems to have everything we need. The only problem is that I cannot read the private keys stored in the database as strings encoded in PEM (certificates / public keys are ok).

If I save a line from the PEM code of the private key from the database to a file, I can run OpenSSL to convert the key to PKCS # 8 format as follows:

openssl pkcs8 -topk8 -inform PEM -outform DER \
              -in private_key.pem -out private_key.der -nocrypt

The result I can encode base64 and then read using this bit of Java / JCA code:

byte[] privateKeyBytes = 
           DatatypeConverter.parseBase64Binary(privateKeyDERcontents);
PrivateKey prKey = 
           KeyFactory.getInstance("RSA").
               generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

, , .

: - PEM?

, , , BouncyCastle:

if (Security.getProvider("BC") == null) {
    Security.addProvider(new BouncyCastleProvider());
}
PEMReader pemReader = new PEMReader(new StringReader(privateKeyPEM));
KeyPair keyPair = (KeyPair) pemReader.readObject();
PrivateKey key = keyPair.getPrivate();

"privateKeyPEM" - PEM , . , JCA KeyPair . : , PEMReader (, , BouncyCastle)?

+1
1

PEM PKCS # 8, , , (----- BEGIN RSA PRIVATE KEY -----), Base64-decode .

-1

All Articles