Tomcat应用访问SSL或https失败的解决办法

一,首先,解决unable to find valid certification path to requested target的问题。

其实就是要生成证书, 让tomcat读取证书

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out
                    .println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP + "lib"
                    + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf
                .getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out
                .println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject "
                    + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out
                .println("Enter certificate to add to trusted keystore or ‘q‘ to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out
                .println("Added certificate to keystore ‘jssecacerts‘ using alias ‘"
                        + alias + "‘");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(‘ ‘);
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}

  在把证书放到$JAVA_HOME/jre/lib/security目录下

要么就是在浏览器里面打开网站的证书, 导出来上传到服务器上, 然后导入到tomcat默认的cacerts

二,然后, 如果问题未解决出现“Certificate doesn‘t match any of the subject alternative names”

这时候, 需要改造代码

a. 方案1:使用HttpURLConnection 请求https地址, 例子如下:

import java.net.HttpURLConnection;

public static HttpURLConnection connectToWeb(String uri) {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return connection;
}

b.方案2:使用SSLConnectionSocketFactory,例子如下:

public static CloseableHttpClient createSSLClientDefault() {
        CloseableHttpClient client = null;
        try {
            SSLContext sslContext = null;
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);//这里的红色部分
            client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        }
        return client;
    }

  

原文地址:https://www.cnblogs.com/plain-heart/p/11381261.html

时间: 2024-11-08 08:26:56

Tomcat应用访问SSL或https失败的解决办法的相关文章

数据库无法访问,用户 NT AUTHORITY/SYSTEM或NT AUTHORITY\NETWORK SERVICE登录失败的解决办法

问题:win7中的在IIS 7.0中,在 Default Web Site 目录下挂一虚拟目录. 在相应的应用程序池 DefaultAppPool 设置标识设置成NetworkService. 但是打开页面后,无法打开登录所请求的数据库,用户登录NT AUTHORITY\NETWORK SERVICE失败. 解决办法: 1.打开sqlserver Management studio,在安全性-登录名 下新建一个登记名NETWORK SERVICE ,设置默认数据库为要访问的数据库. 2.然后选

NetBeans启动Tomcat报“&#39;127.0.0.1&#39; 不是内部或外部命令”启动失败的解决办法

http://blog.sina.com.cn/s/blog_709548200102vgy4.html ———————————————————————————————————————————————————————————————— 问题描述: 新安装的NetBeans8.0.2,安装过程中还一体化安装了内含的Tomcat8.0.15,打开NetBeans运行web工程失败,控制台输出错误信息如下: 启动 Tomcat 失败. *****\build-impl.xml:1164: 部署错误:

python3.7 urlopen请求HTTPS警告&#39;CERTIFICATE_VERIFY_FAILED&#39;解决办法

环境: Mac 10.13.6 python3.7 代码 from urllib.request import urlopen html = urlopen('https://en.wikipedia.org/wiki/Kevin_Bacon',) 报错如下urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) , 大概意思是证书(c

安装weex tookit老是失败的解决办法

安装weex tookit老是失败的解决办法:使用淘宝的镜像来安装 npm install -g [email protected] --registry=https://registry.npm.taobao.org 输入weex出现以下信息,表示安装成功

Ubuntu下sudo apt-get install vim 失败的解决办法

Ubuntu下 执行命令:sudo apt-get install vim 失败 解决办法: 更新一下,命令:sudo apt-get update 再安装即可成功:sudo apt-get install vim Ubuntu下sudo apt-get install vim 失败的解决办法,布布扣,bubuko.com

WCF传输过大的数据导致失败的解决办法

WCF传输过大的数据导致失败的解决办法 WCF服务默认是不配置数据传输的限制大小的,那么默认的大小好像是65535B,这才65KB左右,如果希望传输更大一些的数据呢,就需要手动指定一下缓冲区的大小了. 主要是为binding设置几个最大值属性就可以了,包括服务端和客户端均进行设置,不过配置都是一样的. <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpB

sqlserver sa用户登陆失败的解决办法

sqlserver sa用户登陆失败的解决办法 如下图以此模仿: 1.右键-属性 2.找到安全: 3.勾选如图: 4.sa用户密码重置: 5.服务重启:

iMac 更新XCode 5.0.1 到 5.1.1 失败,解决办法

原因: 因为, 我的 小IPHONE4,在7.0.4版本 超级卡, 昨晚升级到7.1.1 . 今天发现,iMac上的XCODE, 不能识别我的手机,提示说XCODE的版本低,让升级. 之后,XCODE升级过程中,出现问题! 解决办法,如下: 在Finder中,我的电脑(小房子图标) -  资源库 - Developer - XCode   .   一般安装XCode都会安装到这个目录下,      选中XCODE, CMD+DEL 删掉, (或不放心的话, 可以剪切到某个别的路径下),   再尝

Win 2008 R2安装SQL Server 2008“性能计数器注册表配置单元一致性”失败的解决办法

Win 2008 R2安装SQL Server 2008"性能计数器注册表配置单元一致性"失败的解决办法(2011-02-23 19:37:32) 转载▼   今天在惠普服务器上安装数据库2008时,在进行数据库安装检测时总是有一点通不过,提示"性能计数器注册表配置单元一致性失败".以前在其他的服务器上安装都没有碰到过这个问题.开始以为系统没有装好,后面重装了还是一样的.但同一张系统盘在IBM等其他服务器安装系统后,再安装数据库没有出现此问题,很是令人费解.后来在网