How can I read a BouncyCastle private key PEM file using JCA? [duplicate]

倖福魔咒の 提交于 2019-12-02 03:21:03

问题


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).

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:

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

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

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

This private key matches the public key stored as expected, i.e. I can round-trip from plaintext to ciphertext and back.

The question I have is: can I directly read the original PEM encoding somehow?

EDIT

Here is a bit of code that reads the strings in question using 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();

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)?


回答1:


Key inside of PEM file is already stored in PKCS#8 format, so if it is not encrypted with password you can just remove headers (-----BEGIN RSA PRIVATE KEY-----), Base64-decode input, and get the needed bytes.



来源:https://stackoverflow.com/questions/14228282/how-can-i-read-a-bouncycastle-private-key-pem-file-using-jca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!