KeyStoreUtil { public static void updateWithServerPems(KeyStore pKeyStore, File pServerCert, File pServerKey, String pKeyAlgo, char[] pPassword) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException { InputStream is = new FileInputStream(pServerCert); try { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); byte[] keyBytes = decodePem(pServerKey); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(pKeyAlgo); try { privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } String alias = cert.getSubjectX500Principal().getName(); pKeyStore.setKeyEntry(alias, privateKey, pPassword, new Certificate[]{cert}); } finally { is.close(); } } private  KeyStoreUtil(); static void updateWithCaPem(KeyStore pTrustStore, File pCaCert); static void updateWithServerPems(KeyStore pKeyStore, File pServerCert, File pServerKey, String pKeyAlgo, char[] pPassword); static void updateWithSelfSignedServerCertificate(KeyStore pKeyStore);  }
@Test public void testKeyStore() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, InvalidKeySpecException, UnrecoverableKeyException { File serverPem = getTempFile("server/cert.pem"); File keyPem = getTempFile("server/key.pem"); KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]); List<String> aliases = asList(keystore.aliases()); assertEquals(aliases.size(), 1); String alias = aliases.get(0); assertTrue(alias.contains("server")); X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); assertEquals(cert.getSubjectDN().getName(), SERVER_CERT_SUBJECT_DN); RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(alias, new char[0]); assertEquals("RSA", key.getAlgorithm()); RSAPublicKey pubKey = (RSAPublicKey) cert.getPublicKey(); assertEquals("RSA", pubKey.getAlgorithm()); }