PEMImporter { public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword) throws IOException, GeneralSecurityException { PrivateKey key; try { key = createPrivateKey(privateKeyFile, keyPassword); } catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) { throw new GeneralSecurityException("Private Key issues", e); } List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile); if (certificateChain.isEmpty()) { throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile); } KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new)); return keyStore; } private  PEMImporter(); static KeyStore loadTrustStore(File certificateChainFile); static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword);  }
@Test public void testParsingPKCS1WithoutPassword() throws IOException, GeneralSecurityException { KeyStore keystore = PEMImporter.loadKeyStore(pemCert, privkeyWithoutPasswordPKCS1, ""); assertEquals(1, keystore.size()); assertTrue(keystore.containsAlias("key")); assertEquals(1, keystore.getCertificateChain("key").length); }
@Test public void testParsingPKCS1WithPassword() throws IOException, GeneralSecurityException { KeyStore keystore = PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS1, "test"); assertEquals(1, keystore.size()); assertTrue(keystore.containsAlias("key")); assertEquals(1, keystore.getCertificateChain("key").length); }
@Test(expected = GeneralSecurityException.class) public void testParsingPKCS1WithWrongPassword() throws IOException, GeneralSecurityException { PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS1, "nottest"); }
@Test public void testParsingPKCS8WithoutPassword() throws IOException, GeneralSecurityException { KeyStore keystore = PEMImporter.loadKeyStore(pemCert, privkeyWithoutPasswordPKCS8, ""); assertEquals(1, keystore.size()); assertTrue(keystore.containsAlias("key")); assertEquals(1, keystore.getCertificateChain("key").length); }
@Test public void testParsingPKCS8WithPassword() throws IOException, GeneralSecurityException { KeyStore keystore = PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS8, "test"); assertEquals(1, keystore.size()); assertTrue(keystore.containsAlias("key")); assertEquals(1, keystore.getCertificateChain("key").length); }
@Test(expected = GeneralSecurityException.class) public void testParsingPKCS8WithWrongPassword() throws IOException, GeneralSecurityException { PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS8, "nottest"); }