Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I read a BouncyCastle private key PEM file using JCA?
    primarykey
    data
    text
    <p>In one of our applications private keys are stored using BouncyCastle's PEMWriter. At the moment I am investigating if we can get rid of the BouncyCastle dependency since Java 7 seems to have everything we need. The only issue is that I can not read the private keys stored in the database as PEM-encoded strings (the certificates/public keys are fine).</p> <p>If I save the PEM-encoded string of the private key from the database to a file I can run OpenSSL to convert the key to PKCS#8 format like this:</p> <pre><code>openssl pkcs8 -topk8 -inform PEM -outform DER \ -in private_key.pem -out private_key.der -nocrypt </code></pre> <p>The resulting output I can base64 encode and then read using this bit of Java/JCA code:</p> <pre><code>byte[] privateKeyBytes = DatatypeConverter.parseBase64Binary(privateKeyDERcontents); PrivateKey prKey = KeyFactory.getInstance("RSA"). generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); </code></pre> <p>This private key matches the public key stored as expected, i.e. I can round-trip from plaintext to ciphertext and back.</p> <p>The question I have is: can I directly read the original PEM encoding somehow?</p> <p><strong>EDIT</strong></p> <p>Here is a bit of code that reads the strings in question using BouncyCastle:</p> <pre><code>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(); </code></pre> <p>The "privateKeyPEM" is the PEM encoded string in the database, otherwise this example is self-contained. Interestingly it already uses the JCA KeyPair object as output. To rephrase my original question: can I do the equivalent of the code above without depending on PEMReader (and in turn quite a few other BouncyCastle classes)?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload