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 {
                // First let's try PKCS8
                privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
            } catch (InvalidKeySpecException e) {
                // Otherwise try PKCS1
                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();
        }
    }
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 ( ) ; } }
Update a key store with the keys found in a server PEM and its key file.

@param pKeyStore   keystore to update
@param pServerCert server certificate
@param pServerKey  server key
@param pKeyAlgo    algorithm used in the keystore (e.g. "RSA")
@param pPassword   password to use for the key file. must not be null, use <code>char[0]</code>
for an empty password.