Нужна помощь по вызову службы TLS 1.2 https из клиента Java 1.4 - PullRequest
0 голосов
/ 17 сентября 2018

Я сталкиваюсь с проблемой при вызове вызова RestAPI (который выполняется на Java 1.8 и TlS 1.2) с использованием вызова postmethod из клиентского приложения Java 1.4. Я написал ниже код клиента, и я в конечном итоге с проблемой ниже.

Я предоставляю необходимые файлы .jks в хранилище доверенных сертификатов и хранилище ключей.

Ошибка:

>java.security.KeyStoreException 
>at com.ibm.jsse.bg.<init>(Unknown Source) 
>at com.ibm.jsse.bo.a(Unknown Source) 
>at com.ibm.jsse.bo.engineInit(Unknown Source) 
>at javax.net.ssl.KeyManagerFactory.init(Unknown Source) 
>bundles.ubuntu.vas.tiaa.AuthSSLProtocolSocketFactory.createKeyManagers(AuthSSLP>rotocolSocketFactory.java:223) 

Код:

    AuthSSLProtocolSocketFactory authSSLProtocolSocketFactory = new 
        AuthSSLProtocolSocketFactory(new URL("file:C:/cert/testwithsigner.jks"), "password1", 
            new URL("file:C:/cert/testwithsigner.jks"), "password1"); 
    authSSLProtocolSocketFactory.createSocket("sample.intranet",8443); 
    final PostMethod post = new PostMethod("https://sample.intranet:8443/ext/ref/callservice"); 
    HttpClient httpClient = new HttpClient();   
    post.setRequestHeader("Content-type", "application/json"); 
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2"); 
    final int status = httpClient.executeMethod(post); 
    final InputStream is = post.getResponseBodyAsStream(); 
    final StringBuffer content = new StringBuffer(); 
    final String charset = post.getResponseCharSet(); 

Код:

   public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory {

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class);

    private URL keystoreUrl = null;
    private String keystorePassword = null;
    private URL truststoreUrl = null;
    private String truststorePassword = null;
    private SSLContext sslcontext = null;


    public AuthSSLProtocolSocketFactory(
        final URL keystoreUrl, final String keystorePassword, 
        final URL truststoreUrl, final String truststorePassword)
    {
        super();
        this.keystoreUrl = keystoreUrl;
        this.keystorePassword = keystorePassword;
        this.truststoreUrl = truststoreUrl;
        this.truststorePassword = truststorePassword;
    }

    private static KeyStore createKeyStore(final URL url, final String password) 
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
    {
        if (url == null) {
            throw new IllegalArgumentException("Keystore url may not be null");
        }
        LOG.debug("Initializing key store");
        KeyStore keystore  = KeyStore.getInstance("jks");
        InputStream is = null;
        try {
            is = url.openStream(); 
            keystore.load(is, password != null ? password.toCharArray(): null);
        } finally {
            if (is != null) is.close();
        }
        return keystore;
    }

    private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 
    {
        if (keystore == null) {
            throw new IllegalArgumentException("Keystore may not be null");
        }
        LOG.debug("Initializing key manager");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
        if(password != null && password.toCharArray()!= null)
        kmfactory.init(keystore, password.toCharArray());
        return kmfactory.getKeyManagers(); 
    }

    private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException
    { 
        if (keystore == null) {
            throw new IllegalArgumentException("Keystore may not be null");
        }
        LOG.debug("Initializing trust manager");
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(keystore);
        TrustManager[] trustmanagers = tmfactory.getTrustManagers();
        for (int i = 0; i < trustmanagers.length; i++) {
            if (trustmanagers[i] instanceof X509TrustManager) {
                trustmanagers[i] = new AuthSSLX509TrustManager(
                    (X509TrustManager)trustmanagers[i]); 
            }
        }
        return trustmanagers; 
    }

    private SSLContext createSSLContext() {
        try {
            KeyManager[] keymanagers = null;
            TrustManager[] trustmanagers = null;
            if (this.keystoreUrl != null) {
                KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
                //if (LOG.isDebugEnabled()) {
                    Enumeration aliases = keystore.aliases();
                    while (aliases.hasMoreElements()) {
                        String alias = (String)aliases.nextElement();                        
                        Certificate[] certs = keystore.getCertificateChain(alias);
                        if (certs != null) {
                            LOG.debug("Certificate chain '" + alias + "':");
                            for (int c = 0; c < certs.length; c++) {
                                if (certs[c] instanceof X509Certificate) {
                                    X509Certificate cert = (X509Certificate)certs[c];
                                    System.out.println(" Certificate " + (c + 1) + ":");
                                    System.out.println("  Subject DN: " + cert.getSubjectDN());
                                    System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                                    System.out.println("  Valid from: " + cert.getNotBefore() );
                                    System.out.println("  Valid until: " + cert.getNotAfter());
                                    System.out.println("  Issuer: " + cert.getIssuerDN());
                                }
                            }
                        }
                    }
             //   }
                keymanagers = createKeyManagers(keystore, this.keystorePassword);
            }
            if (this.truststoreUrl != null) {
                KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
                if (LOG.isDebugEnabled()) {
                    Enumeration aliases = keystore.aliases();
                    while (aliases.hasMoreElements()) {
                        String alias = (String)aliases.nextElement();
                        LOG.debug("Trusted certificate '" + alias + "':");
                        Certificate trustedcert = keystore.getCertificate(alias);
                        if (trustedcert != null && trustedcert instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate)trustedcert;
                            LOG.debug("  Subject DN: " + cert.getSubjectDN());
                            LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                            LOG.debug("  Valid from: " + cert.getNotBefore() );
                            LOG.debug("  Valid until: " + cert.getNotAfter());
                            LOG.debug("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
                trustmanagers = createTrustManagers(keystore);
            }
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(keymanagers, trustmanagers, null);
            return sslcontext;
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
            throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
        } catch (KeyStoreException e) {
            LOG.error(e.getMessage(), e);
            throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
        } catch (GeneralSecurityException e) {
            LOG.error(e.getMessage(), e);
            throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
        }
    }

    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }



    public Socket createSocket(String host, int port)
        throws IOException, UnknownHostException
    {
        return getSSLContext().getSocketFactory().createSocket(
            host,
            port
        );
    }


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...