为什么我的 HTTPS 错误来自 Jboss 调用而不是来自 java 主方法调用?

Why I have HTTPS error from Jboss call and not from java main method call?

我对这个问题很困惑。我有 HTTPS 调用。我使用 JDK 6.0.45。我无法更新 JDK 因为我正在工作的项目很旧。想象一下,我有这样的代码。

        HttpGet get = new HttpGet(urlToRead);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(get);

当我运行从主要 class 开始这段代码时,我遇到了这种类型的错误:

javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1708)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1691)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1222)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:535)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:403)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at hu.barion.BarionServiceWorker.getPOST(BarionServiceWorker.java:52)
    at hu.barion.BarionServiceWorker.exchangeMoney(BarionServiceWorker.java:111)
    at hu.barion.BarionServiceWorker.main(BarionServiceWorker.java:94)
Caused by: java.lang.RuntimeException: Could not generate DH keypair
    at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:114)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverKeyExchange(ClientHandshaker.java:559)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:186)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
    ... 13 more
Caused by: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)
    at com.sun.crypto.provider.DHKeyPairGenerator.initialize(DashoA13*..)
    at java.security.KeyPairGenerator$Delegate.initialize(KeyPairGenerator.java:627)
    at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:107)
    ... 20 more

好的。我也找到了解决方法。我在网上找到了这个解决方法。

Security.addProvider(new BouncyCastleProvider());

真的很好用!我没问题!

但是会发生什么Jboss服务器调用时?

16:10:48,835 INFO  [Server] Root Deployment Filename: jboss-service.xml
16:10:48,836 INFO  [Server] Starting General Purpose Architecture (GPA)...
16:10:48,976 INFO  [ServerInfo] Java version: 1.6.0_45,Sun Microsystems Inc.
16:10:48,977 INFO  [ServerInfo] Java VM: Java HotSpot(TM) 64-Bit Server VM 20.45-b01,Sun Microsystems Inc.
16:10:48,977 INFO  [ServerInfo] OS-System: Windows 7 6.1,amd64
16:10:49,140 INFO  [Server] Core system initialized
16:10:49,874 INFO  [Log4jService$URLWatchTimerTask] Configuring from URL: resource:log4j.xml
16:10:49,914 INFO  [WebService] Using RMI server codebase: http://localhost:8083/
16:10:49,977 INFO  [NamingService] Started jndi bootstrap jnpPort=1099, rmiPort=1098, backlog=50, bindAddress=localhost/127.0.0.1, Client SocketFactory=null, Server SocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076
16:10:50,871 INFO  [Embedded] Catalina naming disabled
16:10:50,979 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
16:10:51,169 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8443
16:10:51,169 INFO  [Catalina] Initialization processed in 281 ms
16:10:51,169 INFO  [StandardService] Starting service jboss.web
16:10:51,171 INFO  [StandardEngine] Starting Servlet Engine: Apache Tomcat/5.5.9
16:10:51,183 INFO  [StandardHost] XML validation disabled
16:10:51,194 INFO  [Catalina] Server startup in 25 ms
....
....
....
16:10:54,641 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
16:10:54,672 INFO  [ChannelSocket] JK: ajp13 listening on localhost/127.0.0.1:8009
16:10:54,676 INFO  [JkMain] Jk running ID=0 time=0/13  config=null
16:10:54,681 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8443
16:10:54,687 INFO  [Server] JBoss (MX MicroKernel) [4.0.2 (build: CVSTag=JBoss_4_0_2 date=200505022023)] Started in 5s:851ms

....
....
....

javax.net.ssl.SSLException: java.lang.ArrayIndexOutOfBoundsException: 64
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1708)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1691)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1222)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:535)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:403)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at hu.barion.BarionServiceWorker.getHTML(BarionServiceWorker.java:70)
    at hu.barion.BarionServiceWorker.validateUser(BarionServiceWorker.java:157)
    at hu.barion.Services.verifyUser(Services.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.azry.ess.manager.ServiceProxy.invokeAnnotatedMethod(ServiceProxy.java:338)
    at com.azry.ess.manager.ServiceProxy.invokeMethod(ServiceProxy.java:279)
    at com.azry.ess.manager.ServiceProxy.invokeMethod(ServiceProxy.java:204)
    at com.azry.ess.manager.ServiceProxy.execute(ServiceProxy.java:96)
    at com.azry.ess.manager.ServiceManagerImpl.executeSevice(ServiceManagerImpl.java:91)
    at com.azry.ess.connector.nci.NCI.execute(NCI.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:388)
    at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:283)
    at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:319)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
    at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
    at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at ge.bog.commons.log4j.catalina.RequestTimestampValve.invoke(RequestTimestampValve.java:24)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 64
    at com.sun.crypto.provider.TlsPrfGenerator.expand(DashoA13*..)
    at com.sun.crypto.provider.TlsPrfGenerator.doPRF(DashoA13*..)
    at com.sun.crypto.provider.TlsPrfGenerator.doPRF(DashoA13*..)
    at com.sun.crypto.provider.TlsMasterSecretGenerator.engineGenerateKey(DashoA13*..)
    at javax.crypto.KeyGenerator.generateKey(DashoA13*..)
    at com.sun.net.ssl.internal.ssl.Handshaker.calculateMasterSecret(Handshaker.java:753)
    at com.sun.net.ssl.internal.ssl.Handshaker.calculateKeys(Handshaker.java:716)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:873)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:241)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
    ... 59 more

如果我添加或不添加 bouncyCastle 提供程序,当通过 Jboss 完成调用时,我会遇到相同的错误。但是如果我 运行 java 文件,来自 main() mehtond,它没有错误。

private Logger logger = Logger.getLogger(SSLExcludeCipherConnectionHelper.class);

private String[] exludedCipherSuites = { "_DHE_", "_DH_" };

private String trustCert = null;

private TrustManagerFactory tmf;

public void setExludedCipherSuites(String[] exludedCipherSuites) {
    this.exludedCipherSuites = exludedCipherSuites;
}

public SSLExcludeCipherConnectionHelper(String trustCert) {
    super();
    this.trustCert = trustCert;
    // Security.addProvider(new BouncyCastleProvider());
    try {
        this.initTrustManager();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void initTrustManager() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new ByteArrayInputStream(trustCert.getBytes());

    Certificate ca = null;
    try {
        ca = cf.generateCertificate(caInput);
        logger.debug("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);
}

public String get(URL url) throws Exception {
    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory osf=context.getSocketFactory();


    //SSLParameters params = context.getSupportedSSLParameters();
    List<String> enabledCiphers = new ArrayList<String>();


    for (String cipher : osf.getSupportedCipherSuites()) {
        boolean exclude = false;
        if (exludedCipherSuites != null) {
            for (int i = 0; i < exludedCipherSuites.length && !exclude; i++) {
                exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
            }
        }
        if (!exclude) {
            enabledCiphers.add(cipher);
        }
    }

    String[] cArray = new String[enabledCiphers.size()];




    enabledCiphers.toArray(cArray);

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

    urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
    urlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    urlConnection.setRequestMethod("GET");
    urlConnection.setUseCaches(false);
    urlConnection.setAllowUserInteraction(true);
    urlConnection.setRequestProperty("Content-Type", "text/html");

    SSLSocketFactory sf = context.getSocketFactory();
    sf = new DOSSLSocketFactory(sf, cArray);
    urlConnection.setSSLSocketFactory(sf);

    BufferedReader rd = null;

    if (urlConnection.getResponseCode() == 200) {
        rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    } else {
        rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
    }


    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    return result.toString();

}

public String post(URL url, String json) throws Exception {
    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory osf=context.getSocketFactory();


    List<String> enabledCiphers = new ArrayList<String>();

    for (String cipher : osf.getSupportedCipherSuites()) {
        boolean exclude = false;
        if (exludedCipherSuites != null) {
            for (int i = 0; i < exludedCipherSuites.length && !exclude; i++) {
                exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
            }
        }
        if (!exclude) {
            enabledCiphers.add(cipher);
        }
    }

    String[] cArray = new String[enabledCiphers.size()];
    enabledCiphers.toArray(cArray);

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sf = context.getSocketFactory();
    sf = new DOSSLSocketFactory(sf, cArray);
    urlConnection.setSSLSocketFactory(sf);

    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");

    urlConnection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
    urlConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    urlConnection.setUseCaches(false);
    urlConnection.setAllowUserInteraction(true);
    urlConnection.setRequestProperty("Content-Type", "application/json");


     OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
     wr.write(json);
     wr.close();




    BufferedReader rd = null;

    if (urlConnection.getResponseCode() == 200) {
        rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    } else {
        rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    return result.toString();

}

rivate class DOSSLSocketFactory extends javax.net.ssl.SSLSocketFactory {

    private SSLSocketFactory sf = null;
    private String[] enabledCiphers = null;

    private DOSSLSocketFactory(SSLSocketFactory sf, String[] enabledCiphers) {
        super();
        this.sf = sf;
        this.enabledCiphers = enabledCiphers;
    }

    private Socket getSocketWithEnabledCiphers(Socket socket) {
        if (enabledCiphers != null && socket != null && socket instanceof SSLSocket)
            ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);

        return socket;
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return getSocketWithEnabledCiphers(sf.createSocket(s, host, port, autoClose));
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return sf.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        if (enabledCiphers == null)
            return sf.getSupportedCipherSuites();
        else
            return enabledCiphers;
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return getSocketWithEnabledCiphers(sf.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port) throws IOException {
        return getSocketWithEnabledCiphers(sf.createSocket(address, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException,
            UnknownHostException {
        return getSocketWithEnabledCiphers(sf.createSocket(host, port, localAddress, localPort));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localaddress, int localport)
            throws IOException {
        return getSocketWithEnabledCiphers(sf.createSocket(address, port, localaddress, localport));
    }

}