After we spent the weekend to bring our version to version 143 to 154, I publish the lessons learned, hoping this will save some time for someone in the future.
1) The PKI eXtention API from BC has been moved to its bank. I racked my brains to find PemParser at bcprov-jdk15on-154.jar. The implementation of PemParser is in bcpkix-jdk15on-154.jar. Needless to say, the pkix drum is dependent on the bc kernel.
2) The PEMReader class is not available in the latest version 154. This has been replaced by PemParser.
3) Reading an open certificate from a file on disk:
Security.addProvider(new BouncyCastleProvider()); File file = new File("c:/mycert.crt"); X509Certificate cert = null; PEMParser pemParser = new PEMParser(new FileReader(file)); Object object = pemParser.readObject(); if (object instanceof X509CertificateHolder) { X509CertificateHolder holder = (X509CertificateHolder)object; cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); } if (cert == null) { throw new Exception("mycert.crt" + " doesn't contain X509Certificate!"); } return cert;
4) Reading a secret key with password protection from disk:
Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = null; File file = new File("c:/myprivate.key"); PEMParser pemParser = new PEMParser(new FileReader(file)); Object object = pemParser.readObject(); if (object instanceof PEMEncryptedKeyPair) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) object; PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build("strongpasswordfor_myprivate.key".toCharArray()); keyPair = converter.getKeyPair(ckp.decryptKeyPair(decProv)); } return keyPair;
5) When reading a string certificate, this usually happens when we want to perform SSL authentication and transfer the client certificate to the web server to the application server in the Http request header:
Security.addProvider(new BouncyCastleProvider()); X509Certificate cert = null; String myClientCert = "-----BEGIN CERTIFICATE----- CERTCONTENTS -----END CERTIFICATE-----" String cert1 = myClientCert.replaceAll("-----BEGIN CERTIFICATE-----", "").replaceAll("-----END CERTIFICATE-----", "").replaceAll(" ", System.lineSeparator()); int ind = cert1.lastIndexOf(System.lineSeparator()); cert1 = new StringBuilder(cert1).replace(ind, ind + System.lineSeparator().length(), "").toString(); cert1 = BEGIN_CERT + cert1 + END_CERT; PEMParser pemParser = new PEMParser(new StringReader(cert1)); Object object = pemParser.readObject(); if (object instanceof X509CertificateHolder) { X509CertificateHolder holder = (X509CertificateHolder)object; cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); } return cert;
6) Of course, add error handling, exception management, and cleanup to your liking.