user8568429
user8568429

Reputation: 21

SSLContextBuilder fails to loadKeyMaterial

I'm trying to use Apache httpclient-4.5.5 (with httpcore-4.4.9) to obtain the server certificate from a server that applies 'mutual SSL'. I'm creating an SSLContext as follows:

        final String keystorePass = Configuration.getInstance().getItem(EmittentProperties.keystorePass);
    final String kmopEncKeyPass = Configuration.getInstance().getItem(EmittentProperties.kmopEncKeyPass);
    final String kmopEncKeyAlias = Configuration.getInstance().getItem(EmittentProperties.kmopEncKeyAlias);

        //1.Create the SSLContext and SSLConnectionSocketFactory
    SSLContext sslContext;
    try {
        sslContext = SSLContexts.custom()
            .loadKeyMaterial(keystoreFile.getFile(), keystorePass.toCharArray(), kmopEncKeyPass.toCharArray(), new PrivateKeyStrategy() {
                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    return kmopEncKeyAlias;
                }})
            .loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }})
            .build();
    } catch (Exception e) {
        logger.error("Error initializing SSLContext: " + e.getMessage(), e);
        throw new FatalException(e.getMessage(), e);
    }
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

However it always returns "java.security.UnrecoverableKeyException: Cannot recover key" on the loadKeyMaterial(...). While debugging this method I can see that he succesfully loads the keystore and that it contains the keys I created in it. However when subsequently trying to load the key entry associated with the password kmopEncKeyPass it returns the UnrecoverableKeyException.

My (JKS) keystore has two (self-signed) entries 'kmop-enc' used for the SSL handshake and 'kmop-sign' for SSL signing of messages. The password for the alias kmop-enc (parameter kmopEncKeyPass) is the same as the password for the keystore (parameter keystorePass). With the custom PrivateKeyStrategy I want to make sure 'kmop-enc' is returned as alias and not 'kmop-sign' (which has a different password).

Verifying my keystore with keystore-explorer.org shows everything is OK with my keystore. Any ideas on why it throws an UnrecoverableKeyException?

Upvotes: 1

Views: 10394

Answers (1)

user8568429
user8568429

Reputation: 21

Needed to add .setKeyStoreType("JKS") before calling .loadKeyMaterial(...).

Upvotes: 1

Related Questions